GML Visual Creating an instance using a variable.

G

Gabriel_Sajjad

Guest
When creating an instance, is it possible to use a variable containing the object name instead of the object name itself?
Whenever I try doing this, it results in an error.
 

TsukaYuriko

☄️
Forum Staff
Moderator
Yes, that is possible, as long as "object name" means, for example, obj_player, not a string with the value "obj_player". The former is an object ID, the latter is text and has as much to do with an object as an apple (an actual specimen of the fruit) has to do with a piece of paper that says "apple".

If you receive an error message, always post the full error message.
 
I do that sometimes for easy sprite management.
Say I have a couple of "teams" each with equivalent characters animations, I will use a variable called "sprite_string", which will essentially be the sprite name as a string.
So I could have something like:
GML:
//Define race in create
race = "orc";

//Define state in Step event (probably a switch statement)
state = "idle";
//Get a string corresponding to sprite
sprite_string = "spr_" + state + "_" + race;

var _spr = asset_get_index(sprite_string); //THIS IS A POINTER TO spr_idle_orc

draw_sprite( x, y, _spr);
asset_get_index() takes a string and points to the asset of that name, so if you organise your naming conventions good, you can get away with a lot with it.
 
Top