I cover handling of subsidiary instances in the "Finding the Right Instance" section of this article:
What's the Difference: Objects and Instances
Created or copied instance. instance_create() (GMS 1.x and legacy) / instance_create_layer() and instance_create_depth() (GMS 2.x) and instance_copy() return the ID of the created or copied instance. NEVER use instance_nearest() to establish this relationship --- something else could be closer by.
Subsidiary instance(s). Same as created or copied instance. If the subsidiary instance needs to reference its creator, the creator should assign its instance ID to an instance variable in the subsidiary instance. Conversely, if the creator needs to reference its subsidiary (or subsidiaries), it must store the return value of instance_create() (GMS 1.x and legacy) / instance_create_layer() or instance_create_depth() (GMS 2.x) immediately. NEVER use instance_nearest() to establish or maintain this relationship --- being the closest does NOT imply being the most relevant, especially in close quarters.
When you create the subsidiary instance, you make it remember its exact originator like this (NOT with
instance_nearest() for reasons that should be obvious to you by now):
Code:
with (instance_create_layer(x, y, "higherlayer", obj_subsidiary)) {
owner = other.id;
}
Then in the subsidiary's Step event:
Code:
if (instance_exists(owner)) {
x = owner.x;
y = owner.y;
} else {
instance_destroy();
}
You need to
stop believing that
id and
instance_nearest() are the only sources of instance IDs. If you keep working with the assumption that these are the only sources, you'll suck at GML forever. At the very least, you should know that these return or contain instance IDs when applicable:
- Basic collision functions: instance_place() and instance_position()
- Extended collision functions: collision_point(), collision_circle(), collision_ellipse(), collision_line(), collision_rectangle()
- All built-in functions that generate new instances: instance_create_layer(), instance_create_depth() and instance_copy()
- other.id in a Collision event (the one from the event selector, NOT collision checks in the step event) or a with block (which refers back to the calling instance)
More finer points on collision functions are available on
this article, most importantly the difference between
instance_place() and
instance_position().
You should also go over everything you currently believe must take object IDs, and check in the Manual whether they take instance IDs. Way too many rookies synthetically limit themselves to object IDs, and needlessly struggle in multi-instance environments. In particular, the variable reference dot (
subject.variable) also accepts instance IDs on its left side. As a general rule, the only place in GML that accepts object IDs but not instance IDs is the
obj parameter in built-in functions starting with
instance_create_*() or
object_*().