Question: How do you destroy an instance in GameMaker?


In GameMaker, destroying an instance removes it from the room and frees up the memory that was allocated for it. To destroy an instance, you can use the instance_destroy() function within an instance's code block.

Here is an example of how to use instance_destroy():

// This code will destroy the current instance instance_destroy();

If you want to destroy another specific instance, you must reference that instance by its ID:

// Assume 'enemy' is the instance id of the enemy object you want to destroy with (enemy) { instance_destroy(); }

You can also destroy an instance from within a collision event or any other event by simply calling instance_destroy() without referencing a specific instance ID, which defaults to destroying the calling instance itself.

It's important to note that when an instance is destroyed, it will not run any more code in the step in which it was destroyed. However, Destroy event code will still be executed, allowing you to perform clean-up tasks such as saving information or creating particles.

When using instance_destroy(), here are some best practices:

  • Make sure there are no references to the destroyed instance after you call instance_destroy(). Accessing a destroyed instance will result in an error.
  • Use the Destroy event of the object to handle any necessary clean-up actions for the instance.
  • Consider the timing of when you're destroying an instance to avoid gameplay issues or errors.

The above examples are valid in both GameMaker Studio 1.4 and GameMaker Studio 2.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.