Using a Switch Statement instead of Else ifs

While playing along with the tutorial, I thought I’d see if I couldn’t use a switch statement. Somebody out there may be interested in what I did, so here is the code containing the enum switch statement.

private enum States {cell, straw, door_0, door, bucket};
private States gameState;
void Start () {
	gameState = States.cell;
}

// Update is called once per frameS
void Update (){
	switch (gameState) {
	case States.straw:	
		state_straw ();
		break;
	case States.bucket:
		state_bucket();
		break;
	case States.door:
		state_door();
		break;
	 case States.door_0:
	 	state_door_0();
	 	break;
	default:
		state_cell();
		break;
	}
1 Like

Switches are nice, and great for static conditions.
They are easier to read in most cases, and easier to add conditions to.

The example you used is actually a good example of when to use a switch instead of an if/then.
You have limited, defined states, so you can have limited defined cases.

If/then is better for variable conditions.

if playerpos.x == enemypos.x

When both your your needle and your haystack are variable and changing, that is where if/then statements excel.
They are also better for comparators, less than, greater than, not equal, or multiple conditions.

2 Likes

i generally found Switch statement to work best with States, such as the example above when you have pasted, besides that, i do feel like IFand Else are the way to go.

2 Likes

Privacy & Terms