• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GML [SOLVED] How can I use object name in switch statement?

MartinK12

Member
I've created this simple code and depending what kind of object is selected I want to perform different actions on it, but looks like I always get default case. I don’t know where I messed up? Thank You for pointing my mistake :)

Code:
if mouse_check_button_pressed(mb_left) {
instance = instance_position(mouse_x, mouse_y, all);

if instance_exists(instance) {
    ins_id = instance;
    obj_id = ins_id.object_index;
    obj_name = object_get_name(obj_id);
}

switch (obj_name) {
    case obj_menu_sell: {
        //do some stuff to obj_menu_sell
    } break;
    
    default: { 
        show_message("case DEFAULT - obj_name: " + string(obj_name));
        //do some stuff to all other cases
    }
    break;
}       
}
 

FrostyCat

Redemption Seeker
Resource IDs are not strings, stop treating them like one.

object_index holds a resource ID, it is a numeric value. object_get_name() returns strings. You need to cut out the needless middleman, and also consider the case where the click isn't hitting anything.
Code:
if mouse_check_button_pressed(mb_left) {
  var instance = instance_position(mouse_x, mouse_y, all);
  if (instance != noone) {
    switch (instance.object_index) {
      case obj_menu_sell:
        //do some stuff to obj_menu_sell
      break;
      default:
        show_message("case DEFAULT - obj_name: " + object_get_name(instance.object_index));
      break;
    }
  }
}
 

MartinK12

Member
@FrostyCat “are not strings” so I just tried it with quotation marks in the first case like this case ("obj_menu_sell"): and it worked.

But of course Your code is so much better compared to mine. Thank You.
I also added the case where the click isn't hitting anything so it should cover all possible scenarios.
Code:
if mouse_check_button_pressed(mb_left) {

  var instance = instance_position(mouse_x, mouse_y, all);
  if (instance != noone) {
    switch (instance.object_index) {
      case obj_menu_sell:
        //do some stuff to obj_menu_sell
      break;
      default:
        show_message("case DEFAULT - obj_name: " + object_get_name(instance.object_index));
      break;
    }
  }

else show_message("instance = noone"); //and do some other stuff

}
Thank You :)
 
Top