Making raycast ignore multiple layers

I know how to make the raycast ignore a layer but I want it to ignore layers 9 and 10 but collide with the rest of the layers.

Currently, the raycast ignores layer 9.

// Bit shift the index of the layer (9) to get a bit mask
  var layerMask = (1 << 9);
layerMask = ~layerMask;

if (Physics.Raycast(transform.position, transform.forward, Hit , Range, layerMask))
	{

It is much easier to declare a variable that is typecast as LayerMask, then in the Inspector, simply tick the layers that you wish to be detected by the raycast. As a test, create a new script, at the top put

var myLayerMask : LayerMask;

Now save this script, go back to Unity and attach the script to an empty gameObject or the camera (it doesn’t matter, this is just a test). Now look in the inspector, click on the drop-down menu then tick the layers you wish to be acknowledged. This is much easier than trying to implement the bitshift method in the documentation. Now you’ve seen how it works, simply use :

var myLayerMask : LayerMask;

// in a function
if ( Physics.Raycast(transform.position, transform.forward, Hit, Range, myLayerMask) )
{
    // Do Stuff
}

layerMask = 1 << LayerMask.NameToLayer (“layerX”); // only check for collisions with layerX

layerMask = ~(1 << LayerMask.NameToLayer ("layerX")); // ignore collisions with layerX

LayerMask layerMask = ~(1 << LayerMask.NameToLayer ("layerX") | 1 << LayerMask.NameToLayer ("layerY")); // ignore both layerX and layerY

Make sure you’re not passing in the layer mask in the distance argument position.

Do This

    if (Physics.Raycast(transform.position, transform.forward, out hit, Mathf.Infinity, SelectionLOSCheckMask))

NOT THIS

    if (Physics.Raycast(transform.position, transform.forward, out hit, SelectionLOSCheckMask))

Here’s how you ignore any layers you want:

using namespace System;

private int layerMask = Convert.ToInt32(“11111111111111111111100011111111”, 2);

this ignores layers 8,9,10 (where the zeroes are)

Remember the lowest order bit is zero-indexed - that means layer 8 is the 9th position from the right.

[SerializeField] private LayerMask ignoreMe;

if (Physics.Raycast(transform.position, transform.transform.forward, out hit, range, ~ignoreMe))
{

    }

YOU CAN CHOOSE MORE THAN 1 LAYERS IN THE INSPECTOR. JUST CLICK FOR EX. PLAYER AND THEN THE OTHERS YOU WANT TO BE IGNORED.

Unity 2021.3.11f1 version

The easiest way to choose is this I think:

[SerializeField] private LayerMask Name;
And then you can check the layers you want in the inspector.

Just in case anyone is making the same mistake I did:

hit.transform.gameObject

is not the same as

hit.collider.transform.gameObject

Turns out I was getting super confused because the hit with my layermaks was “Returning” on the parent of the hit box. It was working properly, I was just finding the wrong thing.