- Home /
Raycast ignoring layers that it should not
I want to ignore layer 9, but only layer 9. What i am experincing is that it does ignore layer 9 but for some reason that i don't understand it also ignores objects I have on layer 11 (Seems like it ignores alle other layers as well - except from the default layer 0). This is the code i'm using to cast the ray
if (Physics.Raycast(rangeRay.transform.position, (rangeTarget.GetComponent<UnitStats>().rangeRay.transform.position - rangeRay.transform.position), out SelectRangeTargetHit, rayDistance, 9))
What am I doing wrong?
Answer by Neamtzu · Jan 18, 2018 at 01:45 PM
The easiest solution will be to use a variable of type LayerMask assigned in inspector to select which layers to be visible for raycast. Otherwise you'll have to use bitwise operators to indicate the affected layers.
//assign layers in inspector
public LayerMask mask;
if (Physics.Raycast(rangeRay.transform.position, (rangeTarget.GetComponent<UnitStats>().rangeRay.transform.position - rangeRay.transform.position), out SelectRangeTargetHit, rayDistance, mask))
Answer by Bonfire-Boy · Jan 18, 2018 at 01:54 PM
You're doing 2 things wrong.
First, the layer(s) you pass through to RayCast should be those you want to include, not those you want to ignore.
Second, you're passing through the index to your layer, rather than a LayerMask as required by the RayCast function. A LayerMask is a bitmask representing a set of Layers, rather than a single layer.
Your 9
, interpreted as a LayerMask, gives layers 0 and 3 (because 9 = 1+8 = 1^0 + 1^3). So yes, you should expect your RayCast to ignore all layers apart from those 2.
The simplest fix is to change the call so that you're passing through a LayerMask containing everything apart from layer 9, like this...
int layerMask = 1 << 9; // a layermask containing only layer with index 9
layerMask = ~layerMask; // invert the mask so it represents all layers except layer 9
if (Physics.Raycast(rangeRay.transform.position, (rangeTarget.GetComponent<UnitStats>().rangeRay.transform.position - rangeRay.transform.position), out SelectRangeTargetHit, rayDistance, layerMask))// and so on
This is much the same as an example in the docs: https://docs.unity3d.com/Manual/Layers.html and if you don't follow it I would recommending googling for "bitmask" to find out more about the concept.