Use layer name for LayerMask instead of Layer number for ignoring collideres while RayCasting

Hello everyone,

I have a trigger, and I have flying objects.
Whenever my flying objects enter the trigger, they will stop moving.

Till now everything is working.

when objects are clicked, they are destroyed, I need a LayerMask to ignore the Trigger,
since whenever the objects are inside the sphere they don’t get hit by the ray.

So according to this link I have been achieve this, thanks to alucardj.
But I need to do this with the layer name, since I might have 15-20 layers and don’t want
each time go to tag manager to see the number of the layer.

My 10th layer is named “transparent” and I tried this,

layerMask.value = LayerMask.NameToLayer("transparent");

and I put this line of code in the start function, instead of

layerMask = 1 << 10;

but no result… Can SomeOne tell me how to use the layer name, or al least what does
the << syntax explain.

private LayerMask layerMask;

void Start()
  layerMask = 1 << 10;
  layerMask = ~ layerMask;

if(Physics.Raycast(ray.origin, ray.direction  ,out hit , Mathf.Infinity , layerMask.value))
	 if (Input.GetMouseButtonUp(0))
		if(hit.transform.tag == "targetObject")

The function LayerMask.NameToLayer doesn’t return a layermask but the layer index. So you still have to bitshift by this index:

int mask = 0;
mask |= (1 << LayerMask.NameToLayer("someLayerName"))
mask |= (1 << LayerMask.NameToLayer("someOtherLayerName"))

mask = ~mask;

But as InfiniBuzz said, just make your LayerMask variable public, then you have a dropdown in the inspector to select the layers you want. The value property will contain the ready to use layer-mask. Depending on how you want to select them you might still want to invert the value:

public LayerMask ignoreLayers;


int mask = ~ ignoreLayers.value;

Men, just use this :

Mathf.Log(collisionlayerMask.value, 2)

It’s that simple (I searched for a while for this so, here it is)
(It’s the logarithm of the number in base 2 → it’s the opposite of the 2^x function)

I don’t comment something often but I was too amazed to see why people struggled so much with bit-twisting…
You’re welcome :slight_smile:


the bitwise shift operator is used to shift bits in vairables. It’s a way to mask bits, you can read more here: MSDN bitwise shift reference

However I solved a similar issue by just making the layerMask public and assigned it via Inspector.

public LayerMask layerMask;

and then as you did


in the Raycast.

Hope it helps for you too.

Also see Bunny83’s answer to get some clearance :slight_smile: