Making raycast ignore multiple layers

时间:2023-03-09 09:16:53
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.

I would do it the other way round: declare the variable private and use the SerializeField attribute. This way you can edit the variable in the inspector and keep it private so other scripts can't directly access it.

Of course when you don't want to show it in the inspector (to be able to change the layermask) you have to choose the layers in your code manually.

I take the example from the OP:

  1. var layerMask =(1<<9);
  2. layerMask |=(1<<13);
  3. layerMask |=(1<<15);
  4. layerMask =~layerMask;

Or in one line:

  1. var layerMask =~((1<<9)|(1<<13)|(1<<15));

This would exclude layer 9, 13 and 15.

Keep in mind that the IgnoreRaycastLayer should also be ignored. You can use the Physics.kIgnoreRaycastLayerconstant which is the layermask for the layer2 (has a value of 4 == 1 << 2 ). So just add this:

    1. [...]
    2. layerMask |=Physics.kIgnoreRaycastLayer;
    3. layerMask =~layerMask;
    4. [...]