Im currently working through the create with code tutorial and testing things out and seeing what works and stuff. I’m onto the 2nd one where you make a script to destroy food and animals as they go off screen using if statements. Now I’ve learnt the if statement and understand it. so the food going off top of screen has an if statement but now the animals that go off bottom of screen use an else if statement which seems to be the same as the if statement. I have done the code to destroy animals with an if statement to see if it would work and it does. so question is what is the point using else if statement when it does exactly the same thing?
The code inside the if statement gets called if its true.
Else if, would indicate the first “if” was not true.
There’s a button at the top here to put your code example, but im on a phone so here is an example photo from google.
In this example,
If it happen to be that animal == Animal.Mouse
It’s going to go down that if, if else, until it finds match. When its true, it will run only the code inside that set of brackets.
And finally Else means nothing was a match, just do this one
Ok looking back at your question … So why use this instead of just a bunch of if statements.
All separate if statements would also get the right answer, yes. However as it gets more complex it starts to make sense that you want only one result from this singular block of if, if else.
In some scenarios two if statements could both be correct and you may not want that.
Also, the code has a default else answer if everything is false.
Also, its faster where if the first check is true, none of the other else checks get called. Where using all if statements it checks everything all the time
else if
will basically “link” a chain of if-statements and prevent them from running as soon as any one of them is true.
Image you have a chain of multiple if-statement that do some sort of expensive operation to evaluate a condition.
Here’s an exaggerated example using GameObject.Find
, which is a pretty slow operation.
if(GameObject.Find("Thing 1") != null) {
}
if(GameObject.Find("Thing 2") != null) {
}
if(GameObject.Find("Thing 3") != null) {
}
if(GameObject.Find("Thing 4") != null) {
}
if(GameObject.Find("Thing 5") != null) {
}
Let’s say that I only need to know if any one of of these objects exist to perform some action, and I don’t need to care if any others exist.
Now let’s say that “Thing 2” was found.
With the way I have it setup currently, it will still check for “Things 3, 4 & 5” even though it already found one. This is a waste of computation that can be solved using else if:
if(GameObject.Find("Thing 1") != null) {
}
else if(GameObject.Find("Thing 2") != null) {
}
else if(GameObject.Find("Thing 3") != null) {
}
else if(GameObject.Find("Thing 4") != null) {
}
else if(GameObject.Find("Thing 5") != null) {
}
Now, if “Thing 2” is found in the same scenario, all the remaining conditions after will be skipped this time.