GM: switch

From GMpedia.org Wiki

Jump to: navigation, search

switch (value)
 

Type: statement
Limitations: none
The correct title of this article is switch (value). It appears incorrectly here because of technical restrictions.
switch (value)
{
 case a:  {coding break}
 case b:  {coding break}
 case c:  {coding break}
 case d:  {coding break}
 default: {coding}
}

What the switch statement does is take value, compare it to a number of case's, if value equals a certain case then the corresponding block is executed. It is important to have the break statement included in the block because otherwise if case b is chosen, the code of case c and case d will also be executed, it is however not required. The switch statement is an alternative to a large number of if statements, it is also faster (fps wise) and easier to debug, it also makes your coding nicer to look at. There is no limit to the number of case's you can have. If none of the case's are matched then default coding is executed, it is not necessary to have a default statement.


[edit] Example

// Restart the player at the last checkpoint he's touched.
switch (global.checkpoint)// Returns a number 1 - 4
{
 case 1:
  // Create the player at the first checkpoint
  instance_create(obj_checkpoint01.x,obj_checkpoint01.y-12,obj_player);
 break;
 case 2:
  // Create the player at the second checkpoint
  instance_create(obj_checkpoint02.x,obj_checkpoint02.y-12,obj_player);
 break;
 case 3:
  // Create the player at the third checkpoint
  instance_create(obj_checkpoint03.x,obj_checkpoint03.y-12,obj_player);
 break;
 case 4:
  // Create the player at the fourth checkpoint
  instance_create(obj_checkpoint04.x,obj_checkpoint04.y-12,obj_player);
 break;
 default:
  // Create the player at the first checkpoint as no other was chosen
  instance_create(obj_checkpoint01.x,obj_checkpoint01.y-12,obj_player);
}

[edit] See Also

This article was originally found at the Game Maker Knowledge Base, contributed by Abyssal_Nuclei.
See the talk page for details
Personal tools