HOWTOGAMEDEV ALPHA

How to raycast onto specific layers in Unity3D

Use the debug.drawline command in Unity3d to draw lines on the screen during play and visualize your vectors
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.
Select the objects you want to hit with the raycast and assign them to the layer you will be targetting.
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");

}

Posted August 2015 // Unity 5.0.0f4