Solved
What is ( : ) punctation and "case" used for? Example below
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyScriptFile : MonoBehaviour
05 {
06 //Define possible states for enemy using an enum
07 public enum EnemyState {CHASE, FLEE, FIGHT, HIDE};
08
09 //The current state of enemy
10 public EnemyState ActiveState = EnemyState.CHASE;
11
12 // Use this for initialization
13 void Start () {
14 }
15
16 // Update is called once per frame
17 void Update ()
18 {
19 //Check the ActiveState variable
20 switch(ActiveState)
21 {
22 case EnemyState.FIGHT:
23 {
24 //Perform fight code here
25 Debug.Log ("Entered fight state");
26 }
27 break;
28
29
30 case EnemyState.FLEE:
31 case EnemyState.HIDE:
32 {
33 //Flee and hide performs the same behaviour
34 Debug.Log ("Entered flee or hide state");
35 }
36 break;
37
38 default:
39 {
40 //Default case when all other states fail
41 //This is used for the chase state
42 Debug.Log ("Entered chase state");
43 }
44 break;
45 }
46 }
47 }
Answer by NoseKills · Sep 29, 2017 at 04:25 PM
A "switch case" is a way to compare a variable against a set of possible values and perform different actions based on the value.
Explanations and examples here
int someInt = Random.Range(0, 5);
...
switch (someInt)
{
case 0: Debug.Log("it's 0");
break;
case 1: Debug.Log("it's 1 this time");
break;
default:
Debug.Log("it's 2, 3, or 4");
}
// Does the same as
if (someInt == 0) {
Debug.Log("it's 0");
} else if (someInt == 1) {
Debug.Log("it's 1 this time");
} else {
Debug.Log("it's 2, 3, or 4");
}
Answer by Litleck · Sep 29, 2017 at 05:15 PM
Cases are basically like an if statement with if elses so one case would be if example == value then it would run the script completing the switch statement.
switch (example) //The variable you want to check goes in these brackets
{
case 0:
{
//This will execute when example variable = 0
break;
}
}
I treat switch statements like a if but much more simple. Hopefully I helped you and let me know if you have any questions.
I'll appreciate it if you could click accept answer on $$anonymous$$e, thanks.
Answer by Somi_ · Sep 29, 2017 at 05:10 PM
Thank you but what is : used for? Why not ; ???
: Is basically saying run and ; is the end part so : in case 0: will run and ; will end the line like on break;