The "Switch" Statement

This section deals with the uses of "switch" in GameMaker: Studio.

In a number of situations you want to let your instances complete an action depending on a particular value. You can do this using a number of consecutive "if" statements but when the possible choices gets above two or three it is usually easier to use the "switch" statement. A switch statement has the following form:

switch (<expression>)
{
case <expression1>: <statement1>; ... ; break;
case <expression2>: <statement2>; ... ; break;
...
default: <statement>;
}


This works as follows:

Note that multiple case statements can be placed for the same statement. Also, the break is not required, and if there is no break statement the execution simply continues with the code for the next case statement. This means that you can create a hierarchy "switch" in which different sections of code are run depending on the input value. here is an example of a typical "switch" from a game:

{
switch (keyboard_key)
   {
   case vk_left:
   case ord("A"):
      x -= 4;
      break;
   case vk_right:
   case ord("D"):
      x += 4;
      break;
   case vk_up:
   case ord("W"):
      y -= 4;
      break;
   case vk_down:
   case ord("S"):
      y += 4;
      break;
   }
}


The above code uses "switch" to check for a keyboard event and then compares that to the cases listed. If it meets any of the required values then the corresponding code is executed. Note how in the code we have used the way that "switch" can check multiple cases and continue if no break is encountered to permit various keys to be used to get the same result. This is just one of the ways that you can permit multiple configurations for movement in your games.


Back: GML Overview
Next: The "Break" Statement
© Copyright YoYo Games Ltd. 2018 All Rights Reserved