How do you iterate values from variable that use Enum Flags?

How do you iterate values from variable that uses Enum Flags?

I tried using Enum Flags like this, but I dont know to get iteration of all values from variable that use the Enum Flags.

    public class Tester : MonoBehaviour
    {
        [System.Flags]
        public enum TestEnum
        {
            NONE = 0,
            ALL = ~0,
            option1 = 1 << 1,
            option2 = 1 << 2,
            option3 = 1 << 3
        }

        public TestEnum variable;

        private void CheckEnum()
        {
            // I dont know how to iterate values from variable that use Enum Flags
            foreach (var item in variable)
            {
                switch (item)
                {
                    case TestEnum.option1:  Debug.Log("Option 1");
                        break;
                    case TestEnum.option2:  Debug.Log("Option 2");
                        break;
                    case TestEnum.option3:  Debug.Log("Option 3");
                        break;
                    default:
                        break;
                }
            }
        }
    }

Switching over TestEnum. is correct. Iterating over all entries of an enum is a bit unusual, but since this is a C# topic you will find lots of information online about it: .net - How to loop through all enum values in C#? - Stack Overflow

If you have any specific usecase in your mind and need help with that, feel free to ask about that, but given the context, im not sure what else to reply right now :slight_smile:

Err… that one discuss about how to iterate all types existing from source enum not values from variable that use the enum as type. And I what I am looking for is Enum Flags not normal enum.

Nevermind. I found out you need to use has flag to check the value from Enum Flags.

        private void CheckEnum()
        {
            if (variable.HasFlag(TestEnum.option1))
            {
                Debug.Log("Option 1");
            }
            if (variable.HasFlag(TestEnum.option2))
            {
                Debug.Log("Option 2");
            }
            if (variable.HasFlag(TestEnum.option3))
            {
                Debug.Log("Option 2");
            }
        }
1 Like