Hello, everyone, today i found an interesting bug about LayerMask.NameToLayer.
As follows, if i use a static string save layer name , then use LayerMask.NameToLayer i will get a wrong value. But if i use a const string, the result is correct.
Are you getting this error in the console during compile and run?:
UnityException: NameToLayer is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour. See “Script Serialization” page in the Unity Manual for further details.
I get this error in Unity 2017.4.
Edit: nvm, I added the code to a MonoBehaviour instead of a static class.
This is not a Unity bug, it’s a problem with how your code is written. This concerns the order of static field declarations. The order of static fields matters. The static field used as the parameter to NameToLayer will be null. NameToLayer presumably falls back to looking for the first empty string layer when null is passed, which would be layer index 3 (a builtin layer). You should hover over the orange warning squiggle in Rider. That probably shows a warning about field initialization. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Also, you should use code tags when posting code. https://discussions.unity.com/t/481379
Thanks for your answer !!!
Now I know how to avoid these question.
I test that put the static string before NameToLayer is also correct.
But rely on static field order is a bad idea.