- Home /
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! :D
Answer by Commoble · Mar 19, 2017 at 01:07 AM
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.
Or maybe just use an interface which each different class implements. Base classes usually restrict you too much and couples the classes too much.
Though the bit we have seen of the actual setup is not really enough to pin point or recommend a concrete solution. It highly depends on the actual goal. That's the general problem with questions that only focus on a particular solution for a problem without mentioning the actual problem.
I see, I'm only doing this to make my function less expensive. But I get the idea. I'm not quite sure how to use enums to be honest, at first I thought it is a set of variables that could be use individually but turns out it doesn't work that way. I think setting them as different classes would do a better job, thanks for all the advice!
Your answer
![](https://koobas.hobune.stream/wayback/20220612113420im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Switch-case with enum 1 Answer
Operator '==' cannot be used! 2 Answers
Enum is thought to be a float? 2 Answers
Switch case using enum javascript 2 Answers
Enum and Variable with similar name resulting in error 1 Answer