set ray only when raycast a specific layer

hey! i want to debug a raycast, but only when it hits a specific layer, if it hits somehwere else, do nothing. here is the code so far:

using UnityEngine;
using System.Collections;

public class RaytoMouse : MonoBehaviour {

	public float distance = 50f;

	//replace Update method in your class with this one
	void FixedUpdate () 
		//if mouse button (left hand side) pressed instantiate a raycast
			//create a ray cast and set it to the mouses cursor position in game
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast (ray, out hit, distance)) 
				//draw invisible ray cast/vector
				Debug.DrawLine (ray.origin, hit.point);
				//log hit area to the console

The ray cast system allows you to specify a layer mask. It’s described in detail in the docs:

But they don’t show an example.

The simplest way to use it is to make use of the layer mask utility in unity:

//get the mask to raycast against either the player or enemy layer
int layer_mask = LayerMask.GetMask("Player", "Enemy");

//or this would be just player
//int layer_mask = LayerMask.GetMask("Player");

//or this would be player, enemy or cows!
//int layer_mask = LayerMask.GetMask("Player","Enemy","Cows");

//do the raycast specifying the mask
if (Physics.Raycast (ray, out hit, distance, layer_mask))


The docs for it are here:

Basically the layer mask is just an integer. For each layer in your game (up to 32), a corresponding ‘bit’ is set in your mask. The raycast system can use this 32 bit mask to work out what layers you’re interested in. Unity’s LayerMask utility is a convenient way of constructing these masks so you don’t have to think too hard about bits and masks and stuff!


Hi, I have my Player to move when I touch on the screen using

   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit[] hits = Physics.RaycastAll(ray, 200);

    foreach (RaycastHit hit in hits)
            if (hit.collider.CompareTag("Terrain"))
                newLocFound = true;
                dirLocation = hit.point;

but I also have a button on my GUI which is ment to cast my attack.
Every time when I touch the screen the player moves to the direction even I am touching the button to attack.
What should I use to solve that issue?