Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

LayerMask.value gives wrong value [solved]

Discussion in 'Scripting' started by QuinnWinters, Oct 24, 2016.

  1. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    313
    The layer selected in the LayerMask dropdown is layer number 16. When I do the following it prints that the value is 65536. How do I make it print the correct layer value of 16?

    Code (CSharp):
    1.     public LayerMask myLayer;
    2.  
    3.     void Start () {
    4.  
    5.         print (myLayer.value);
    6.  
    7.     }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,351
    It's not wrong. It's a bitmask; layer 16 = 2^16 = 65536. You can figure out why it's a bitmask instead of an integer if you think about it for a second. :)

    --Eric
     
    Kiwasi likes this.
  3. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    313
    Aah that makes sense. Thanks for the quick answer. After researching that some it seems using LayerMask.NameToLayer is a far more simple route to go even though it means having to type in layer names as strings instead of choosing a layer from a dropdown menu.
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,351
    Well, but that's going to result in a typo sooner or later. I'd suggest staying away from strings where possible for that reason.

    --Eric
     
  5. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    313
    Too true, thank you for the suggestion. I enum'd the strings to keep that from happening.
     
  6. Lastered

    Lastered

    Joined:
    May 13, 2021
    Posts:
    1
    I know this is an old post but i hope to add my simple solution to the pile.

    You can just use logarithm to get the raw value.
    Since Quinn was getting a returned number of 65536 and Eric made the good observation that it is returning 2^16, you can just plug in 65536 and 2 into a logarithm to get the layer number you're looking for.
    Code (CSharp):
    1. var rawValue = layerMask.value;
    2. var layerValue = Mathf.Log(rawValue, 2);