GML Blog‎ > ‎

Linking Objects in Game Maker

Did you ever want to create an enemy that has not only a body part, but a laser beam attachment that always aims at you. Well, it's not that hard to do for one enemy. Now try to do that for all the 30 enemies in that level. Things would get tricky if you didn't know this: All instances in Game Maker have what is called an id and an instance_id. Game Maker uses these to keep track of instances in the room. The id of an object is basically a unique number given to it when it is created. The instance_id is an id that every instance has.The instance_id is dependent not on how many instances in total there are in the room, but on how many instances of that object there are. Here's an example that will clear up much of what I have failed to explain in words.

There are 10 objects in the room.  Two obj_circles, 5 obj_triangles, and 3 obj_rectangles.  Lets say that when the objects were added to the room, they were added in the order mentioned above.  Here is a graph of the objects and their ids:

               
instance_id    id

obj_circle      0              100000
obj_circle      1              100001

obj_triangle    0              100002
obj_triangle    1              100003
obj_triangle    2              100004
obj_triangle    3              100005
obj_triangle    4              100006

obj_rectangle   0              100007
obj_rectangle   1              100008
obj_rectangle   2              100009


Notice how the ids start with 100000.  Why?  I really don't know.  Maybe to reserve space for behind the sceans code that Mark may have used to make Game Maker function the way it does.  Anyway, the point is, when you do an instance_create(yata yata), the function returns the id of the instance that was created.  If you do a laserBeamGun = instance_create(rightArmX,rightArmY,obj_laserBeamGun) then you can reference the object through the use of laserBeamGun since it holds the id of said object.  You can now access it like you would with any other object.  Here is some sample code to illustrate how you might use the laserBeamGun instance in a game:

laserBeamGun.ammo = 100
laserBeamGun.armed = 1
laserBeamGun.accuracy = .5

The execution of the code above will only affect the obj_laserBeamGun attached to that enemy.  Try it out.  For me, it really extended Game Maker's possibilities.

[Attention - This page uses a mono spaced font: Courier New.  If your OS/browser does not have this font, some texts may not be aligned correctly]

Affiliates