
First we need to create a Unity Layer. In the top right corner you'll find a dropdown with all the layers in your project. You can choose to edit this list.
The first 7 layers are standard and cannot be edited. Add your target layer on the 8th position.
Declare the layer in code. This will be used later in the raycast call. We'll call our variable
targetLayer_
//This will assign layer 8
private int targetLayer_ = (1 << 8);
//This will assign layers 8 and 10
private int targetLayer_ = (1 << 8 | 1 << 10);
Time to cast a ray. Let's cast a ray from the
camera through the
mouse cursor into the game.
We'll use the
Physics.Raycast function. In order to fire the ray from the camera into the world we'll need to use the
ScreenPointToRay value with the mouse cursor coordinates.
We'll also need a
RaycastHit object, which will receive the information from this Raycast() function and store it for us to process.
Lastly we provide the
targetLayer_ which defines the layers we are targeting. This variable was declared before hand in step 3. The ray will pass through objects on other layers if it encounters them first.
//create a RaycastHit that will collect the information about the collision
RaycastHit mousehit = new RaycastHit();
//get the cursor coordinates
Vector2 mouseCoords = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
//Physics.Raycast returns true if it hits the target layer
if( Physics.Raycast(Camera.main.ScreenPointToRay(mouseCoords), out mousehit, 1000.0f, targetLayer_) ){
Debug.Log("Hit target");
}else{
Debug.Log("Missed target");
}