- Home /
How can I have a raycast ignore a layer completely?
I got to the point to know how layers work and how to implement them into my code but how can I completely ignore all the objects that are on that layer? and how can I use that correctly in my code without creating any errors or null references?
Answer by ThePersister · Sep 08, 2014 at 03:39 PM
This one should be reasonably easy to answer :)
Hitting a certain layer leads to the usage of a LayerMask. Normally, you'll only be hitting that / those layers. To invert a LayerMask, add a cute "~" (squiggly) in front of it.
Here's some example code. Nero Fires Everything once you click your left mousebutton and then tells you what he hit: https://www.youtube.com/watch?v=1Io0OQ2zPS4
The code:
public LayerMask IgnoreMe;
private Ray ray;
private RaycastHit hit;
void Update()
{
if (Input.GetMouseButtonDown(0))
NeroFiresEverything();
}
public void NeroFiresEverything()
{
// Basic example ray
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000f, ~IgnoreMe))
{
Debug.Log("Get Rekt " + hit.collider.name);
}
}
You can define what layer(s) to Ignore in the Inspector in a supercool dropdown box. Hope that helps, if anything was unclear let me know, otherwise, please accept the answer :)
Answer by ginryu · Nov 05, 2021 at 01:41 PM
I found an important thing about layermasking, layermasking seems to fail on even number layers. the time this happenes is when I bitshift int layerMask = gameObject.layer << gameObject.layer; then I use layerMask = ~layerMask; and use that in the layerMask slot of the raycast function, when tested, I found that the ray would ignore all odd numbered layers 1,3,5,7,9, etc. but the layermask would fail on even layers 2,4,6,8,10 etc