How to use layermask?

I must be doing something very wrong. This is my code:

private LayerMask layerMask = 9;

hitCollidersNormalAttack = Physics.OverlapSphere(issuerPosition, range, layerMask);
if (hitCollidersNormalAttack != null)
{
Debug.Log(hitCollidersNormalAttack.Length);

}

foreach (Collider col in hitCollidersNormalAttack)
{
Debug.Log(col.gameObject.name);

}

Try one of the following instead:

layerMask = 1 << 9

or

LayerMask.GetMask(“Enemy”)

1 Like

When I use:

LayerMask layerMask = 1 << 9;

I only get hits for enemies, and when I use 1 << 8 I get a hit for the player, nothing from the Default layer.

LayerMask.GetMask(“Enemy”) and LayerMask.GetMask(“Player”) returns hits for Enemy and Player respectively, LayerMask.GetMask(“Default”) gives no returns.

Thanks for your suggestions.

This is a mask, one bit per layer, so you need to include everything you care about.

If you want enemies and default, e.g. you would do:

layerMask = (1<<9) | (1<<0)

for players and default:

layerMask = (1<<8) | (1<<0)

(the <<0 isn’t strictly necessary, but it looks consistent)

Of course… using literals isn’t really recommended in a real-world project.

You should be using either

LayerMask.GetMask(“A”, “B”)

or

(1 << LayerMask.NameToLayer(“A”)) | (1<< LayerMask.NameToLayer(“B”))

or if you wanna make life easy, just add a public LayerMask field and set in in the inspector

public LayerMask layerMask

9 Likes

You have no idea how much you helped me with this, it works perfectly!! Thank you so much man, I’ve been wasting almost all day to get this to work, and you solve it in a few minutes. I owe you one :).

2 Likes

hi! The Layers Manual is actually a great resource too :smile: Just for future reference :slight_smile: Glad you were able to get help! :smile: Best of luck!!!

1 Like

Sorry, I misunderstood how to use it completely, I just assumed an int was all that’s needed since that’s what the description in Unity told me to use (when you hover over it):

Collider[ ] OverlapSphere(Vector3 position, float radius, int layerMask) (+ 2 overloads)

And in the parameters description online I found:
layerMask A Layer mask that is used to selectively ignore colliders when casting a ray.

One more question, how come I can’t type: LayerMask.GetMask(“Default”)?

1 Like

ya… i won’t pretend the docs are the most user friendly. lol Often, the information is split between two places the Scripting API and (if it has one) its Manual counter part. :slight_smile: The search bar is your friend in both hehehe (personal learning experience as reference hahaha)

1 Like

It doesn’t help that I’m a complete beginner either ;). I have bookmarked the manual counterpart too, thanks for the suggestion :).

That part is a bug.

1 Like

Alright, thanks for clearing it up.