Single-instance objects referenced by global variables

Guitarmike

Member
Hi,
I'm new to GML but not to programming. I'd like a little advice on best practices. I have a couple of objects in my game for which there is only a single instance and which need to be accessible from many other places around the game. For example, the obj_player and the obj_clock. Currently, to get the player's position in the room from an event in another object, I would do something like this:

Code:
var xx = 0;
var yy = 0;
with (obj_player)
{
    xx = x;
    yy = y;
}
...
Does it make sense, instead, to declare a global variable containing the player object's instance and then access it directly using some thing like

xx = global.player.x

I'm curious how this approach, which feels simpler and more readable, affects things like performance and memory. Or any other things I haven't thought of. Thanks.
 

Simon Gust

Member
Well, no matter how you do it, 2 variable lookup calls are not going to cause even a dent in your performance.
One is clear, making a global player variable would just be slower than refrencing obj_player (a constant) directly (global.player in this case is the same as obj_player, so only performance loss due to an extra global pass).
A with statement is slower in this type of case because you're only accessing 2 variables from the player.
Code:
var xx = obj_player.x;
var yy = obj_player.y;
should suffice.
A case where with statements are faster would be this for example.
Code:
draw_text(obj_player.x, obj_player.y - 40, string(obj_player.max_hp) + " / " + string(obj_player.hp));
draw_text(obj_player.x, obj_player.y - 80, string(obj_player.hspd));
draw_text(obj_player.x, obj_player.y - 120, string(obj_player.vspd));
draw_text(obj_player.x, obj_player.y - 160, string(obj_player.direction));
...
There are so many dot operations that in the end it would be slower and less readable than this
Code:
with (obj_player)
{
    draw_text(x, y - 40, string(max_hp) + " / " + string(hp));
    draw_text(x, y - 80, string(hspd));
    draw_text(x, y - 120, string(vspd));
    draw_text(x, y - 160, string(direction));
}
 
Top