- Home /
Compare layers
I have a script in which I want to compate if an object is in a certain LayerMask but I dont know why it does not work at all.
public LayerMask PlayersLayer; //this camp is set on the inspector
void OnCollisionEnter2D(Collision2D coll)
{
if (LayerMask.LayerToName(coll.gameObject.layer) == LayerMask.LayerToName(PlayersLayer.value))
{
Debug.Log("Explode");
ExplodeBlack();
}
}
Answer by tanoshimi · Jan 06, 2017 at 07:10 PM
You're trying to compare a layer with a layermask, which is incorrect logic. Although both can be represented as integers, they're different things.
The .layer property of your colliding object represents the single layer on which it is placed, an integer in the range [0...31] as defined in the Tags and Layers section of the editor.
The LayerMask variable you're declaring in the inspector is a bitmask. While it too is an integer, the value doesn't mean anything useful numerically - it's just a convenient way of packing 32bits of data representing flags of which masks are on/off.
To test if any given layer has its bit set in a layermask you should use a bit operation:
PlayersLayer.value & 1<< coll.gameObject.layer
Can you tell me how Can I research this about? because I don't know that code structure , i don't know what "<<" means or is used for, nor the single "&"
Your answer
Follow this Question
Related Questions
Check if Layer is in Layermask? 5 Answers
LayerMask for RayCast 1 Answer
Why is Physics.Raycast returning colliders in a layer not included in the layermask? 2 Answers
My LayerMask is not working 1 Answer