Jump to content
  • Advertisement
Sign in to follow this  
rangler

Unity [java] bitmasking and flags

This topic is 4894 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
You could do something like the following:


public static final int MASK_ONE = 1;
public static final int MASK_TWO = 2;
public static final int MASK_FOUR = 4;

// some logic...

if(someValue == (MASK_ONE | MASK_TWO | MASK_FOUR))
{
// do something
}


It really depends on what you are trying to achieve, but this approach should work.

Share this post


Link to post
Share on other sites
Quote:
Original post by Whackjack

if(someValue == (MASK_ONE | MASK_TWO | MASK_FOUR))
{
// do something
}



Better write:

if ((someValue & (MASK_ONE | MASK_TWO)) != 0)
{
// do something if MASK_ONE or MASK_TWO is set
}

Share this post


Link to post
Share on other sites
Two things to consider here:

- First, if you're going to use C/C++ style enums, you must be aware that you have to use bit flags, that is, values must be a power of 2, as it is in Whackjack's example. This is fine and fast, but it can lead to problems if you have a large set of enum constant types.

- To solve this, the SDK 1.5 introduced the implementation of enums. They are backed by the same system, with a limit of 64 if I remember well, which makes people complain a lot about it ;)

However, using enums is quite simpler than the suggested approach if you stick to the java.util.EnumSet class. A bit more on java enums can be found here

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!