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?

4 Answers

4

This one should be reasonably easy to answer :slight_smile:

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 :slight_smile:

Realizing that I could apply the ‘Ignore Raycast’ layer to what I didn’t want the ray to hit fixed this for me. ThePersister’s answer for some reason did not work.

Sorry for necro, but I’ve done exactly what is described here, and now my ray ignores everything, lol. It “was” outputting the tag of stuff it was hitting, and it would show it was hitting different layers. Now that I included “~EnemyLayerMask” it no longer hits the “Enemy” layer (which I selected), nor does it hit any other layers, like the player. It no longer outputs any hits at all.

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