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

How do I check what an object's layer mask is in an if statement

Discussion in 'Scripting' started by Xander_8002, Jul 17, 2022.

  1. Xander_8002

    Xander_8002

    Joined:
    Jul 1, 2022
    Posts:
    13
    I am writing a piece of code where I need to check if an object has a certain layer mask. I am doing a ray cast and this if statement checks a few things and I would like it to also check to see if the object it hits has a specific layer mask but I can't find out how to do that.

    The if statement:
    Code (CSharp):
    1. if(Input.GetKeyDown(KeyCode.E) && Physics.Raycast(transform.position, transform.forward, out hit, 5) && hit.transform.GetComponent<Rigidbody>() && LayerMask == HoldMask)
    2.  
    The last part of that code '&& LayerMask == HoldMask' was my attempt which didn't work.

    I am only a few months into C# so it may seem obvious to many but I don't know. I couldn't find a valid solution online.
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,669
  3. Xander_8002

    Xander_8002

    Joined:
    Jul 1, 2022
    Posts:
    13
  4. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,669
    By the way, I'm not a big fan of all this bit-shift and bit-wise operators. I once wrote a few utility functions to make it easier for myself. I will see if I can find those.

    Edit: I found them. They are written as extension methods for LayerMask. I don't know if that will just make it more confusing.

    Code (csharp):
    1.  
    2.     public static void AddLayer(ref this LayerMask val, int layer )
    3.     {
    4.         val |= 1<<layer;
    5.     }
    6.  
    7.     public static void RemoveLayer(ref this LayerMask val, int layer)
    8.     {
    9.         val ^= 1 << layer;
    10.     }
    11.  
    12.     public static bool Contains(this LayerMask val, int layer)
    13.     {
    14.         return ((val & (1<<layer))>0);
    15.     }
    16.  
    17.  
     
    adamgolden likes this.
  5. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,100
    Note this method does not remove the given layer but toggles it. In order to remove it you would need to do

    Code (CSharp):
    1. public static void RemoveLayer(ref this LayerMask val, int layer)
    2. {
    3.     val &= ~(1 << layer);
    4. }
     
    kdgalla likes this.