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();                                                   
        }
    }

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