Layermask doesn't seem to work

This is quite odd, I’ve used layer masks before with no problems, so not sure what is happening. I’m trying to use a simple layer mask.

int layerMask = 1 << 12;
layerMask = ~layerMask;
Ray ray camera.ScreenPointToRay(new Vector3(x, y, 0));
RaycastHit hit;

if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
{
  Debug.Log("Hit: " + hit.transform.name + " Layer: " + hit.transform.layer);
}

So I want to hit all layers except layer 12, but no matter what I do, it always hits it. I even tried taking out layerMask = ~layerMask (which wouldn’t make any sense) and of course it still hits it. Both times it prints out Layer 12.

Any ideas?

When I’m using Layermasks, my preferred method is to do this:

var mask: LayerMask;

I then use that mask in my Raycast, rather than dealing with bitshifting and all of that.

I realize it’s not an explicit answer to your question, but it will solve your problem.

I have just tested the layer thing and this works fine for me:

int layerMask1 = ~(1<<12);
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, Mathf.Infinity,layerMask1))
    Debug.Log("Hit something " + hit.transform.name + " " + hit.transform.gameObject.layer);

Don’t know whats wrong in your case.