Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

if else vs (?:) , switch case, Destroying enemy code

Notes:

I. Destroying enemy after fixed number of steps: [Starts at: 04min:59sec]
II. if else vs conditional operator (?:): [Starts at:14min:00sec]
III. switch case statement: [Starts at:19min:55sec]

I. Destroying enemy after fixed number of steps: [Starts at: 04min:59sec]

Example Code:
using UnityEngine;
public class ConditionalStatements : MonoBehaviour {
void Start () {

bool collided = false;
float alpha = 100f;
float alphaToReduce = alpha * 0.5f; // 50

Debug.Log ("Before bullet hit alpha= " + alpha); // 100

// if enemy hit by bullet
collided = true;

if ((collided == true) && (alpha >= 100f)) {
alpha = alpha - alphaToReduce;
collided = false;
}
Debug.Log ("After one bullet hit alpha= " + alpha); // 50

// if enemy hit by one more bullet
collided = true;

if ((collided == true) && (alpha >= 50f)) {
alpha = alpha - alphaToReduce;
collided = false;
}
Debug.Log ("After one bullet hit alpha= " + alpha); // 0

if (alpha == 0f) {
Debug.Log ("Destroy Enemy"); // destroying in 2 steps
}
}
}

II. if else vs conditional operator (?:): [Starts at:14min:00sec]

Example Code:
using UnityEngine;
public class ConditionalStatements : MonoBehaviour {
void Start () {
// comparing if else and conditional operator
/*
int flag = (11 % 2 == 0) ? 1 : 0;
Debug.Log (flag);
*/

int flag=0;
if (11 % 2 == 0) {
flag = 1;
} else {
flag = 0;
}
Debug.Log (flag);
}
}

III. switch case statement: [Starts at:19min:55sec]
Used when a variable has more than one alternative values

Syntax:
switch(expression)
{
case const-expression:
statements;
jumping statement;
[default:
statements;
jumping statement;]
}

Example Code:
using UnityEngine;
public class ConditionalStatements : MonoBehaviour {
void Start () {
int choice = 4;
switch (choice) {
case 1:
Debug.Log ("Ceailing fan is on");
break;
case 2:
Debug.Log ("AC is on");
break;
case 3:
Debug.Log ("Table fan is on");
break;
default:
Debug.Log ("Invalid choice");
break;
}
Debug.Log ("Completed");
}
}

Notes:
All cases must end with break statement.
If a case has no statement then it need not be end with break statement.
Even default case must end with break statement.