In GameMaker, you can access variables from other instances (objects) using the dot operator or with specific functions like
instance_find. Here’s how you do it:
If you know the instance ID of the object from which you want to get a variable, you can use the dot operator to access its variables. The instance ID is often obtained when you create an object using
instance_create_depth. For example:
In this code,
obj_Enemy has a variable named
health, and we are accessing it using the instance ID stored in
If you don’t have the instance ID but know that there is only one instance of the object in the room, you can use
instance_find to get the instance ID:
This finds the first instance of
obj_Enemy in the room.
When there are multiple instances of an object and you want any one of them, you could use the object index directly:
This will get the
health variable from the first instance of
obj_Enemy that was created.
You can also use the
with statement to perform operations on all instances of an object. If you just want to retrieve a value once, you should assign it to a variable outside of the
instance_exists before trying to access a variable from another instance to avoid runtime errors.
These are some of the ways you can get a variable from another object in GameMaker. Choose the method that best fits your situation.