I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android?
the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases.
if(hp >= 81)
{
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = true;
hp4.enabled = true;
hp5.enabled = true;
}
else if(hp >= 61)
{
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = true;
hp4.enabled = true;
hp5.enabled = false;
}
else if(hp >= 41)
{
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = true;
hp4.enabled = false;
hp5.enabled = false;
}
else if (hp >= 21)
{
hp1.enabled = true;
hp2.enabled = true;
hp3.enabled = false;
hp4.enabled = false;
hp5.enabled = false;
}
else if (hp >= 1)
{
hp1.enabled = true;
hp2.enabled = false;
hp3.enabled = false;
hp4.enabled = false;
hp5.enabled = false;
}
else if(hp < 1)
{
hp1.enabled = false;
hp2.enabled = false;
hp3.enabled = false;
hp4.enabled = false;
hp5.enabled = false;
}
true
at the start ofUpdate
and then set them tofalse
individually when ahp
is below the threshold (e.g.:if(hp < 81) hp5.enabled = false;
). This way you'd replace theif
-else
chain with just 5if
statements. Although I am not sure why you need to have this inUpdate
in the first place, as you should be able to change those values in the same place where you modifyhp
? \$\endgroup\$if
statements and the concept of cleaning up theseif
statements are as generic as they come. The best way to look at it is to ask yourself if a game developer or a programmer would better answer your question; and if your asking the same thing, when you remove all game-based aspects. Note that for what your asking,I believe CodeReview is the right place, where the close reason suggests StackOverflow. \$\endgroup\$hp.enabled = true
is specific, I would argue that the core component of the question asks about setting bools. The fact that thisbool
is based inUnityEngine
has no effect on the question or answer. \$\endgroup\$