I think it is a problem of misunderstanding, and lack of good documentation from Unity's side, of how the Layers are represented on Editor and how their values really are. If you read documentationIsTouchingLayer's documentation, you can see that just by mere semantics the int you have to provide is that of a layer mask. LayerMasks make use of a technique called bit-masking, which is a technique used to store many flags into a chain of bits, for optimization purposes. So, for example, being an integer a 4 bytes (32 bits) type, you can store up to 32 flags (saving you the need to potentially declare up to 32 bools, for example).
So, if you consulted the links I provided and understood the basics of bit-masking, we can now understand more clearly why the Layers presented on editor are between 0 and 32:
- Layer 0 (Default) = 0 -> 1 << 0 = 1
- Layer 1 (TransparentFX) = 1 -> 1 << 1 = 2
- Layer 2 (IgnoreRaycast) = 2 -> 1 << 2 = 4
- ...
- Layer 32 (CustomLayer) = 32 -> 1 << 32 = 2,147,483,647
- So basically: Layer N (CustomLayer) = N -> 1 << N = 2 raised to the N
So what you must pass are the numbers of the Layers but using bit shifting (so for example, if you wanted to pass the layer 4, you can either pass it as 1 << 4 or 16). And you can also pass multiple layer values, say you want to pass layers 4, 5 and 7:
int layerMask = (1 << 4) | (1 << 5) | (1 << 7)
And that is why the use of an exposed (public or serializable) LayerMask, instead of you yourself doing bit shifting operations, is sometimes the way to go, it does things more easily. So you could do instead:
public class Example : MonoBehaviour
{
public LayerMask layerMask;
public Collider2D ground;
private void Awake()
{ /// LayerMask has an implicit conversion to int
Debug.Log(ground.IsTouchingLayers(layerMask));
}
}
Hope it helps.