SWITCH STATEMENT
We have so far made a decision in our code only by using if, nested-if or series of if-else statements. In the previous section, we were able to get the particle effects into play using a series of if-else statements. However, it made our code look dirty and is cumbersome. An alternative and preferred way is using a Switch Statement.
Switch Statement
A switch statement is a streamlined decision making statement
It is used when we want to make a decision based on the value of one variable and series of different constant that the variable stores (in our case: playerLife)
We already have declared the variable playerLife to be 3. The highest value of playerLife is 3 and the lowest is 0.
I created a new method called FireParticleEffect() to store our switch statement. Inside FireParticleEffect(), a switch statement was written. Common syntax of switch statement is:
switch()
{
//cases are defined within this scope
case <constant>:
statement;
break;
default:
}
We are comparing our playerLife variable so inside the paranthesis we put our variable.
switch (playerLife)
Inside the scope { }, we define series of cases. The case contain the constant that our variable carry.
case 2: is the case when playerLife = 2
provide instruction to do when case happens
after the case instruction is provided, we have to jump out of the case such that none of the other cases are executed. To do this we use
break;
Call Method
Finally FireParticleEffect() method was called in our existing OnCollisionEnter() method
Quick Update
Using similar approach, I completed the particle effects in my game and the result is shown ...