Raycast won't ignore layer 31

Could someone out there help me with this problem? As far as I am aware, the this should force raycast to ignore objects in layer 31. However, after debugging, lo and behold the hitInfo.collider.gameObject.layer is 31. This should be impossible.

hit = Physics.Raycast(ray, out hitInfo, distance, 1 << 31);
Debug.Log(hitInfo.collider.gameObject.layer); // Outputs 31.

The following also has not worked:

This causes the game to break randomly because this code is used by a lot of classes. Perhaps its ignoring everything but layer 31?

hit = Physics.Raycast(ray, out hitInfo, distance, ~(1 << 31));

This? Ditto. Causes game to freeze up:

hit = Physics.Raycast(ray, out hitInfo, distance, 31);

(1<<31) is ONLY objects on 31
~(1<<31) is NOT objects on 31
(31) will not do what you think, and will in fact include layers 1,2,3,45 (its a bitmask!)

just quickly tested and ~(1<<31) ignored a cube on layer 31.

If you really are using all 32 layers, maybe you need to reorganize!

I realized the mistake I made just now: I forgot to also include the ignore layer 2. ~(1 << 2 | 1 << 31)

Though, I tried this once and I dismissed it as not working, though it actually DID work, and something else was messed up. I forgot to set up the collision matrix and because I didn’t stuff wasn’t behaving correctly.

Also, the following code caused unity to barf all over the place:

private static readonly LayerMask _ignoreMask = ~(1<<LayerMask.NameToLayer("MyIgnoreLayerName"))  Physics.IgnoreRaycastLayer;

Basically, the instant this value was evaluated (static values are evaluated lazily), some code within native code land would get stuck in an infinite loop.

Surely that just evaluates to Physics.IgnoreRaycastLayer, unless MyIgnoreLayerName is the same layer, in which case you get a zero

~(1<<x) // = 1 in all positions except x

(1<<y) // = 1 in only y
       // = 1 in only y