Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Bug LayerMask.NameToLayer return wrong value

Discussion in 'Scripting' started by RosickyChe, Mar 30, 2024.

  1. RosickyChe

    RosickyChe

    Joined:
    Mar 30, 2024
    Posts:
    9
    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.

    Unity version is 2022.3.20f1.

    Anyone knows why?




    upload_2024-3-30_12-13-3.png
    upload_2024-3-30_12-13-16.png
    upload_2024-3-30_12-13-30.png
     
  2. ArachnidAnimal

    ArachnidAnimal

    Joined:
    Mar 3, 2015
    Posts:
    1,933
    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.
     
    Last edited: Mar 30, 2024
    CodeSmile likes this.
  3. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    738
    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/d...guide/classes-and-structs/static-constructors
    Also, you should use code tags when posting code.
    https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    Bunny83, CodeSmile, tsukimi and 3 others like this.
  4. RosickyChe

    RosickyChe

    Joined:
    Mar 30, 2024
    Posts:
    9
    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.
     
  5. RosickyChe

    RosickyChe

    Joined:
    Mar 30, 2024
    Posts:
    9
    @Spy-Master give the correct reason