Question: How do I get an object from an ID in GameMaker?


In GameMaker Studio, every instance of an object has a unique identifier (id) that can be used to reference it directly. This id is automatically assigned when the instance is created and can be used to perform operations on the particular instance.

To get an object from its id in GameMaker, you simply use the id value within your code. Here's an example:

// Let's say you have an instance id stored in a variable var instance_id = instance_create_layer(x, y, "Instances", obj_Enemy); // Now you can use `instance_id` to refer to that instance directly instance_id.hitpoints = 10;

In this code snippet, instance_create_layer() creates a new instance of obj_Enemy at the given x and y coordinates on the "Instances" layer and returns the id of the new instance. We store this id in the variable instance_id and then use it to set a property (hitpoints) for that instance.

To get details of the instance such as its object type or check if it still exists, you can use the following functions:

  • object_get_name(object_index) to get the name of the type of object the instance belongs to.
  • instance_exists(id) to check if the instance still exists before trying to access its properties or call its methods.

Here's how you might use these functions:

if (instance_exists(instance_id)) { var object_type = object_get_name(instance_id.object_index); show_debug_message("The instance is of type: " + object_type); }

This checks if the instance still exists before attempting to access its object_index property and then retrieves the object type name using object_get_name().

Remember that you should always ensure an instance exists before trying to interact with it to avoid runtime errors.

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.