Hi Robert,
If there can be only two possibilities then you could have this;
if(value == 1)
{
// do stuff
}
else
{
// do other stuff
}
The code examples you’ve gave in your post, the first could let both statements within the if
statement execute if the value of value
changed at any point in between, as unlikely as it may be, if could happen.
The second is safer, although you are missing an if
in the syntax;
if (value == 0)
{
// ...
}
else if (value == 1)
{
// ...
}
But as you have already stated there can only be two possibilities you don’t really need to have the other condition stated at all, because if it isn’t one it is the other.
Not sure what data type you are using, but 0/1, on/off, true/false, that’s a boolean. So, if you defined your variable as such;
private bool hasFacialHair;
private void DisplayShavingStatus()
{
if(hasFacialHair)
{
Debug.Log("I need a shave!");
}
else
{
Debug.Log("Smooth as the day I was born!");
}
}
In the above, hasFacialHair
is only going to equate to true
if it has been set to true (the same as being set to 1, or on etc etc), so you can reduce the syntax a little further.
If you ever needed to have multiple values then the boolean isn’t going to be your friend, and in that case you may also use a switch
statement instead;
private int hairsOnHead;
private void DisplayBaldnessStatus()
{
switch(hairsOnHead)
{
case 0:
Debug.Log("Oh dear. Oh dear, oh dear!");
break;
case 1:
Debug.Log("One! Shave that bad boy off right now!");
break;
case 2:
Debug.Log("Two! A least they have each other!");
break;
default:
Debug.Log("So dashing! You are quite literally the modern day Prince Charming!");
break;
}
}
I’m not sure why I went down the hair route in this example, nostalgia perhaps, but hopefully the underlying point I was trying to make, makes sense.
Hope this helps