-1

ok so im sorry to be asking, however im trying to make it so that when i press z, a portal appears at my Spr_players coordinates, however if one of them already exists, i want it to be erased and im simply wondering what ive done wrong. Again sorry for bothering. (please note that i am a bad programmer and i appoligize if i broke any rules)

if object_exists(portal)
{
instance_destroy()
action_create_object(portal,Spr_player.x,Spr_player.y)
}
else
{
action_create_object(portal,Spr_player.x,Spr_player.y)
}

1 Answers1

1

The instance_destroy() statement destroys the current self instance which is what is executing the code. You must use the with (<objectID>) {instance_destroy()} syntax to destroy another instance.

As long as there is only one instance of portal in the room this code should work:

if object_exists(portal)
{
with (portal) instance_destroy(); //you should also need a semicolon here to separate
                                  //this statement from the next, it is good practice
                                  //to do this after all statements as I have done.
action_create_object(portal,Spr_player.x,Spr_player.y);
}
else
{
action_create_object(portal,Spr_player.x,Spr_player.y);
}

If there are multiple instances of portal this will only destroy the first one. To destroy all you would have to use a for loop to iterate through them all. Off the top of my mind I can not remember the function to get the ids of all the instances of an object, but it looks like this is not a problem since each time one is created the existing one is destroyed and thus you will only have one a t a time.

Another way of doing this is just to move the existing portal to the new position. The only difference here is that the create event of the portal will not be executed and any alarms will not be reset.

portal.x=Spr_player.x
portal.y=Spr_player.y

Again this will only move the first portal if there are more than one.

PGmath
  • 381
  • 3
  • 16