How to use LayerMask.NameToLayer

I am trying to set the layer to look for during runtime, and I can get it to work just fine if I expose it in the inspector and select a LayerMask from the dropdown. But I want to know how I can do it without picking it in the inspector.

I am trying this:

mask =  LayerMask.NameToLayer("enemy");

Collider[] targetsInRange = Physics.OverlapSphere(transform.position, radius, mask);

But I can see that this does not return the Layer named “enemy”, but 2 other random layers. What am I missing?

you have to convert the layerIndex to a layer mask, I don’t know the appropriate way but try something like this:

int mask=0x01<<LayerMask.NameToLayer(“enemy”);

did it work?

Afraid not =/

Ill just set it using the index int…

did you try
LayerMask.GetMask(“LayerName”);

1 Like

I will give you an advice.
Don’t use LayerMask like this. Create ScriptableObject that will have method
“int GetMask()” or “LayerMask GetMask()”

Than you will be able to drag and drop references to you nicely named layar masks whenever you want.

Why wouldnt I just make a static class with a GetMask() method then? seems like a lot more work making it an SO I have to drag every time, would be the same as exposing a field in the inspector.

LayerMasks in Unity are implemented as a bitmask. I have an essay of a post explaining what bitmasks are here , if you’re unfamiliar. @craig4android 's solution was technically correct. 1 << LayerMask.NameToLayer( "enemy" ) will generate the appropriate bitmask for use with physics. If that snippet didn’t work for you, perhaps there is something else that is causing it not to work. The LayerMask.GetMask method does the same thing and is interchangeable with the above method.

Check to make sure that the objects you are colliding with have the correct layer, and that the sphere is as large you want and in the correct place.

Static class will not be visible in an editor, you would have to create enum.

But thanks to my method.
You would be able to add new masks without editing the code.
So if you have another people working on your project this workflow will be a lot of smoother.
I went that way never looked back.