0

I've just started using gamemaker studio 2 and I've been scratching my head over this one for a while.

I need to be able to destroy a specific instance of my enemy object without using the collision event. Here is my current code:

In my player object:

if (sprite_index = spr_player_attack_left) {
    if (obj_enemy.x > x - 25 && obj_enemy.x < x) {
        obj_enemy.hp--;
    }
}

//detect right
if (sprite_index = spr_player_attack_right) {
    if (obj_enemy.x < x + 25 && obj_enemy.x > x) {
        obj_enemy.hp--;
    }
}

//detect up
if (sprite_index = spr_player_attack_up) {
    if (obj_enemy.y > y - 25 && obj_enemy.y < y) {
        obj_enemy.hp--;
    }
}

//detect down
if (sprite_index = spr_player_attack_up) {
    if (obj_enemy.y < y + 25 && obj_enemy.y > y) {
        obj_enemy.hp--;
    }
}

And in my enemy object:

if (hp <= 0) {
    var attacked = instance_find(obj_enemy, this.id);
    instance_destroy(attacked);
}

Currently there is only one instance of the enemy in the room that registers an attack, and when I attack that instance, all instances are destroyed, while I only want one to be destroyed.

Thanks in advance for any help!

Marco
  • 99
  • 2
  • 6

1 Answers1

0

The reason this is happening is because you are using the object index, and not an index of a specific instance. When you do:

<object_index>.<object_property> eg. obj_enemy.hp

Two things can happen:

  1. If there is one instance currently active in the game, then that instance's variable will be referenced.
  2. If there are two or more instances, then GameMaker can't tell which one you want to reference.

The offending code here are the if statements:

if (obj_enemy.x > x - 25 && obj_enemy.x < x) {
    obj_enemy.hp--;
}

The way you can rewrite them is:

with (obj_enemy) {
    if (x > other.x - 25 && x < other.x) hp--;
}

The same goes for all of the other if statements as well. The with keyword acts as a loop here. You can read it as "go through each instance of obj_enemy and do the code between { ... }". To reference the instance outside the with statement we use other(in this example, other will be the player).

And for the code in the enemy object, you don't have to use instance_find at all. Actually the this.id part is completely invalid, unless you define this as an instance variable before that code runs.

Anyways, the correct version would be:

if (hp <= 0) {
    instance_destroy();
}

The instance_destroy function destroys the instance that is currently in scope(in GMS2 or GMS1 Early Access, you can pass it an additional id of the instance you wish to destroy).