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:

GML Code Example

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


This works as follows:

  • First the expression is executed.
  • Next it is compared with the results of the different expressions after each of the case statements.
  • The execution continues after the first case statement with the correct value, until a break statement is encountered.
  • If no case statement has the right value, execution is continued after the default statement (it is not required to have a default statement, in which case no action will be taken).

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:

GML Code Example

{
 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.





No Examples Submitted

Does this page need better examples? Be the first to Submit

No Edits Suggested

Is this page unclear or not descriptive enough? Suggest an edit to the page and with enough upvotes your changes will be made.

No Questions Have Been Ask

Do you have a question about this page? Ask it Here