Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by Rafes · Jul 30, 2011 at 08:18 PM · layerlayermaskbitwise

Using a bitwise operator with LayerMask

(I searched all over for this and couldn't find a simple Q&A)

I'm trying to test if a GameObject.layer is in a LayerMask.value. e.g.:

 if ((layerMask.value & hitObject.layer) == hitObject.layer)
     Debug.Log(hitObject.name + " is in one of our layers");


When I Debug.Log the test expression, it always prints 0. When try Debug.Log a simple test, such as 3 & 2, it prints 2.

Any Idea why this comparison isn't working?

 (this.layers.value & hitObject.layer)
Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Rafes · Jul 30, 2011 at 08:18 PM 0
Share

As a secondary question, could I just test to see if the return is > 0 to avoid a second look-up?

avatar image Filippopotamus · Mar 07, 2013 at 12:10 AM 3
Share

I like your function. So I made it a bit more compact and put it on a Tools class.

 using UnityEngine;
 
 public class Tools {
 
     public static bool IsInLayer$$anonymous$$ask(GameObject obj, Layer$$anonymous$$ask mask){
         return ((mask.value & (1 << obj.layer)) > 0);
     }
 }

That way you can just access it from anywhere just by doing:

 Tools.IsInLayer$$anonymous$$ask(myGameObject, myLayer$$anonymous$$ask);
avatar image Rafes · Mar 07, 2013 at 12:32 AM 0
Share

That's what we do. Thanks for posting the compact version!

2 Replies

· Add your reply
  • Sort: 
avatar image
19
Best Answer

Answer by Rafes · Jul 30, 2011 at 08:26 PM

There is a great explanation here that I hadn't considered: http://answers.unity3d.com/questions/122586/layermask-vs-1ltlt-gameobjectlayer-.html

I need to 'cast' the object's layer, which is the integer shown in the inspector, in to the masked version, which is used to compare with the LayerMask. For example, layer "6" in 1, 2, 3, 4, 5, 6 needs to be 1, 2, 4, 8, 16, 32

Here is a working function to do this:

 /// <summary>
 /// Checks if a GameObject is in a LayerMask
 /// </summary>
 /// <param name="obj">GameObject to test</param>
 /// <param name="layerMask">LayerMask with all the layers to test against</param>
 /// <returns>True if in any of the layers in the LayerMask</returns>
 private bool IsInLayerMask(GameObject obj, LayerMask layerMask)
 {
     // Convert the object's layer to a bitfield for comparison
     int objLayerMask = (1 << obj.layer);
     if ((layerMask.value & objLayerMask) > 0)  // Extra round brackets required!
         return true;
     else
         return false;
 }


Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Rafes · Jul 30, 2011 at 08:42 PM 1
Share

Its too bad I can't vote for my own post..hint, hint ;)

avatar image chingwa · Feb 06, 2013 at 10:03 PM 0
Share

Perfect! this answer helped me so much, thanks!

avatar image zangad · Feb 11, 2013 at 03:43 AM 0
Share

Very nice function. That helped me a lot.

avatar image Trejdi · Jul 30, 2018 at 01:31 PM 1
Share

For a small improvement ins$$anonymous$$d:

 if ((layer$$anonymous$$ask.value & objLayer$$anonymous$$ask) > 0)  // Extra round brackets required!
          return true;
      else
          return false;

simply

 return ((layer$$anonymous$$ask.value & objLayer$$anonymous$$ask) > 0)  
avatar image Bunny83 Trejdi · Jul 30, 2018 at 01:45 PM 0
Share

Right, most people don't seem to realise what a boolean value actually is. Though the outer brackets aren't needed.

 return (layer$$anonymous$$ask.value & objLayer$$anonymous$$ask) > 0;
avatar image
7
Wiki

Answer by AlexanderPatrick · Aug 25, 2014 at 04:28 AM

I learned about extension methods recently and thought I would contribute to this as well.

 namespace ExtensionMethods {
     public static class LayerMaskExtensions {
         public static bool IsInLayerMask(this LayerMask mask, int layer) {
             return ((mask.value & (1 << layer)) > 0);
         }
         
         public static bool IsInLayerMask(this LayerMask mask, GameObject obj) {
             return ((mask.value & (1 << obj.layer)) > 0);
         }
     }
 }


Which can then be used like this:

 using UnityEngine;
 using ExtensionMethods;
 
 public class LayerMaskTest : MonoBehaviour {
     public LayerMask layerMask;
     
     void OnTriggerEnter2D(Collider2D hitObject) {
         if ( layerMask.IsInLayerMask(hitObject.gameObject) ) {
             Debug.Log(hitObject.name + " is in one of our layers");
         } 
     }
 }




Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image yordis.prieto · Mar 04, 2015 at 05:57 AM 0
Share

I like your idea but I tried and I ended in use a class ins$$anonymous$$d of the namespace. I don't why I am very new with C#.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Layermask (raycast) wont work... 4 Answers

Detecting that I'm clicking a unit even though I'm not? 0 Answers

LayerMask for RayCast 1 Answer

Return Objects hit by raycast, check against a array of all objects? 1 Answer

How to make my raycast also hit deactive objects WITHOUT showing the object? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges