GameMaker Changing the Sprite Of A Specific Instance From A Separate Object

EhMan

Member
Hey, I'm a newbie with GameMaker Studio 2, and I'm running an engine that creates encounters by taking an enemy object and creating an instance of them for each time that enemy appears in a battle. It does this with a separate "battle" object, which manages the fight as a whole.

I'm able to get the instance of the enemy, and I want to be able to change the sprites of specific enemies at a time. Is there a way to do that from the "battle" object, assuming I can get the instances from "battle", such as with sprite_index? Or do I need to do something else, like create a user event or something that gets called?

Thanks in advance!
 

Alice

Darts addict
Forum Staff
Moderator
What you do is basically storing the instance of the enemy in the variable, and then use either "with" statement or dot notation to set the variable.

Using with statement:
GML:
// this is called from "battle" object
var _enemy = /* retrieve the enemy instance here */;
with (_enemy) {
    // will work only if enemy instance is active
    // if enemy instance is deactivated via instance_deactivate_* function
    // then the code inside "with" block won't execute
    sprite_index = spr_enemy_whatever;
}
Using dot notation:
GML:
var _enemy = ...;
_enemy.sprite_index = spr_enemy_whatever; // this works regardless of whether the enemy exists or not
If the name of the variable to be changed is determined by name variable (but it's much rarer case, with statement or dot notation suffices for vast majority of cases):
GML:
var _variable_name = "hp";
var _enemy = ...;

var _current_value = variable_instance_get(_enemy, _variable_name);
variable_instance_set(_enemy, _variable_name, _current_value - 10);

// if you know in advance that variable changed is always "hp"
// you can replace these variable_instance_get/set calls with "_enemy.hp -= 10;"
Hope this helps.
 

EhMan

Member
Thanks! I managed to get it working!

One other issue I am now working on is transitioning from one sprite's animation to another. I essentially have a beginner, loop, and end sprite. Is there a way to have my battle object recognize when the start and end animations finish so I can transition to what should happen next? I can't hardcode it since the animations across my enemies is not going to be consistent.

EDIT: Nevermind, just found sprite_get_number. I could probably use that.
 
Top