I’ve read more than once to NEVER use else if. I even found a response on Unity Answers that said to never use them. The reason I’m writing this question is to know the difference between the two. I’ve experimented with just using if statements and it always works, because the logic always makes sense. It wasn’t until just a few minutes ago that I discovered a situation where else if is the only way to get some code to work:
when I hit the space key "a" becomes true
if(a && Input.GetButtonDown("left"))
{
a = false;
d = true;
}
if(a && Input.GetButtonDown("right"))
{
a = false;
b = true;
}
if(b && Input.GetButtonDown("left"))
{
b = false;
a = true;
}
if(b && Input.GetButtonDown("right"))
{
b = false;
c = true;
}
if(c && Input.GetButtonDown("left"))
{
c = false;
b = true;
}
if(c && Input.GetButtonDown("right"))
{
c = false;
d = true;
}
if(d && Input.GetButtonDown("left"))
{
d = false;
c = true;
}
if(d && Input.GetButtonDown("right"))
{
d = false;
a = true;
}
The above code didn’t work. It was driving me crazy because everything was in order. I decided to try else if on all of them and sure enough it fixed it. When I had them all as regular if’s when I hit “right” while “a” was true nothing would happen. If I hit “left” it would jump to “c” and completely ignore d. No matter what I tried I could never get “d” to = true. In fact hitting “right” would always make “a” true, doesn’t matter which was currently true hitting right made everything else false and “a” true.
Using else if fixed everything. Now I can cycle through a-d. Imagine something like a= start game, b = load, c= options, d= quit, and that they are all next to each other.
This code cycles through them like it would in any game. So my question is: What’s the difference between if and else if?