Optimising if else statements to switch and enums, or are there better methods?

Hello, I’ve hard coded 21 bools to check in my if else statements. Currently i want to optimize them with switch and enums.

To illustrate, here’s an example:

void Activate(Stat stat)
{
        if(stat.box || stat.item)
        {
                  Debug.Log("take item");
                   return;
        }
        else
        {
                 if(stat.light)
                 {
                         stat.light.enabled;
                         return;
                  }
                 else if(stat.enemy)
                 {
                          stat.enemy.Appear();
                 }
        }
}

It goes even lengthier complicated with the rest of the bools integrated. So here’s what I plan to do:

enum StatType {Box = 0, Item = 0, Enemy = 0, Light = 0};

void Start()
{
        ObjectStat();
}

StatType ObjectStat()
{
         if(stat.box)
         {
                  ObjectStat.Box = 1;
         }
         if(stat.item)
         {
                  ObjectStat.Item = 1;
         }
         if(stat.light)
         {
                  ObjectStat.Light = 1;
         }
         if(stat.enemy)
         {
                  ObjectStat.Enemy = 1;
         }
}

void Activate()
{
        switch(ObjectStat)
        {
                   case ObjectStat.Enemy:
                            if(ObjectStat.Light == 0)
                            { 
                                      stat.enemy.Appear();
                             }
                             break;
                   case ObjectStat.Box:
                           //Debug.Log("take the item");
                             break;
                   case ObjectStat.Item:
                           //Debug.Log("take the item");
                             break;
                   case ObjectStat.Light:
                             stat.light.enabled = true;
                             break;
        }
}

Will this be more efficient? Or are there other methods that I’m not aware of? Any ideas or tips are much appreciated! :smiley:

If you’re doing what I think you’re doing – you have a few different object types (Enemy, Box, Item, and Light) and you want them to behave differently, but you want the same thing to activate all of these behaviors, then I suggest making each of these a subclass of some base class. Then you can treat all of these objects the same way, but define the specifics of what they do in their own class.