Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

switch case vs else if ladder, health bar code, state machine

Notes:

I. switch case vs else if ladder : [Starts at: 00min:00sec]
II. Health bar code : [Starts at: 08min:07sec]
III. State machine using swith case : [Starts at: 22min:07sec]

I. switch case vs else if ladder : [Starts at: 00min:00sec]

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");
*/

int choice = 4;
if (choice == 1) {
Debug.Log ("Ceailing fan is on");
} else if (choice == 2) {
Debug.Log ("AC is on");
} else if (choice == 3) {
Debug.Log ("Table fan is on");
} else {
Debug.Log ("Invalid choice");
}
Debug.Log("Completed");
}
}

II. Health bar code : [Starts at: 08min:07sec]

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

/*
int health = 100;
if (health >= 70 && health <= 100) {
Debug.Log ("Green Healthbar");
} else if (health >= 50 && health < 70) {
Debug.Log ("Orange Healthbar");
} else if (health >= 30 && health < 50) {
Debug.Log ("Red Healthbar");
} else {
Debug.Log ("Black Healthbar");
}
*/

int health = 100;
int result = health / 10; // int/int =int

switch (result) {
case 10:
case 9:
case 8:
case 7:
Debug.Log ("Green Healthbar");
break;
case 6:
case 5:
Debug.Log ("Orange Healthbar");
break;
case 4:
case 3:
Debug.Log ("Red Healthbar");
break;
default:
Debug.Log ("Black Healthbar");
break;
}

}
}

III. State machine using swith case : [Starts at: 22min:07sec]

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

int state = 0;

switch (state) {
case 0:
Debug.Log ("New born state");
state = 1;
break;
case 1:
Debug.Log ("Adult state");
state = 2;
break;
case 2:
Debug.Log ("Sick state");
state = 3;
break;
case 3:
Debug.Log ("Dead state");
break;
}

switch (state) {
case 0:
Debug.Log ("New born state");
state = 1;
break;
case 1:
Debug.Log ("Adult state");
state = 2;
break;
case 2:
Debug.Log ("Sick state");
state = 3;
break;
case 3:
Debug.Log ("Dead state");
break;
}

switch (state) {
case 0:
Debug.Log ("New born state");
state = 1;
break;
case 1:
Debug.Log ("Adult state");
state = 2;
break;
case 2:
Debug.Log ("Sick state");
state = 3;
break;
case 3:
Debug.Log ("Dead state");
break;
}

switch (state) {
case 0:
Debug.Log ("New born state");
state = 1;
break;
case 1:
Debug.Log ("Adult state");
state = 2;
break;
case 2:
Debug.Log ("Sick state");
state = 3;
break;
case 3:
Debug.Log ("Dead state");
break;
}
}
}