[DISCUSSION] Clean and Neat way for "define once".

xDGameStudios

GameMaker Staff
GameMaker Dev.
I was looking for a neat way of defining things once for each object or even globally... BUT something that could be done from inside the object itself (maybe create event).
some of the ideas I came up with:

GML:
getSharedData = function() {
    static data = undefined;
    if (data != undefined) return data;
   
    // define instance
   
    return data;
}
sharedData = getSharedData();
PROS: Neat and clean.
CONS: The function `getSharedData` is defined for all instances and it occupies memory unnecessarily.

GML:
if (!variable_global_exists(object_get_name(object_index))) {
    var data;
   
    // define instance

    variable_global_set(object_get_name(object_index), data);
}
sharedData = variable_global_get(object_get_name(object_index));
PROS: Nothing is redeclared or occupies extra memory.
CONS: Not so clean.

I wanted something that could allow for defineOnce and defineOnceGlobal, the first one would defined for the given object and the latter would define on a global scope.
I know this could be easily done with scripts. Put the declaration in a script file inside a function and do something like the first example... but I was looking to maintain everything related to an object somewhere inside the object itself. So this is more of a project management issue.

I would love to hear your ideas!
 

samspade

Member
I think, and I could definitely be wrong, that the answer is neither of these. They key to realizing this is the sentence: "I know this could be easily done with scripts. . . . but I was looking to maintain everything related to an object somewhere inside the object itself"

If you want everything to be contained solely in one instance of one object, then you should only have one instance of the object. If you want many instances of an object to have access to a universal element of data, then that universal element needs to be outside of those instances. Either in a global variable or a single instance of a separate object. GameMaker basically enforces this design since it doesn't allow access to objects inside the game, only specific instances of an object.

Even where GameMaker does allow this (as with structs and static variables where the constructor holds the universal data to the structs) behind the scenes it is essentially doing the above - there is a thing the constructor function - which exists outside of the instances of each struct and that thing holds the static variable.
 
Top