[GameMaker] Utilizing script_execute();

null

Syntax : script_execute(scr, arg0, arg1, arg2, …);

I can’t help but feel that script_execute() is one of the most overlooked functions in GameMaker. The official docs describe it as a way to “pass a script to an instance in a dynamic way”. Lets take a look at a simple way it can be utilized.

Lets say you wanted to make a “Play” button for your game. You go ahead and create a new object called obj_ButtonPlay. You give it a sprite and put some code in the Mouse Left Pressed event. You’ve also added some extra code to make it switch images when the button is highlighted. It works as you expect.

But now, you need an “Options” button. So, again, you make another button, naming it obj_ButtonOptions. You give it a sprite, and put some code in the Mouse Left Pressed event. You also add some more of that fancy code to make it highlight. But now you realise that you need more buttons; MANY MORE! You continue to make a new object for each and every button in your game.

Using script_execute, I like to avoid needing a different object for each button.
We can create ourselves a single button object and, using script_execute, make it do (virtually) whatever we want it to.

This time, we create an object called obj_UIButton and initialize a variable in its Create Event:

// Create Event
onTouchUp = -1;

Secondly, we add some code to the Mouse Left Released event:

// Mouse Left Released Event
if (onTouchUp != -1)
{
script_execute(onTouchUp);
}

Now, we go ahead and create ourselves a new script called “GameStart” and write the code we need to start the game:

// GameStart()
audio_play_music(bgmAwesomeSong, true);
room_goto(rmBattleZone);

Then create another script called “GameQuit”:

// GameQuit()
GameSave();
audio_stop_music();
room_goto(rmMainMenu);

We can now dynamically create both required buttons and attach these scripts.

buttonPlay = instance_create(320, 250, obj_UIButton);
buttonPlay.onTouchUp = GameStart;
buttonPlay.sprite_index = spr_ButtonPlay;

buttonQuit = instance_create(320, 350, obj_UIButton);
buttonQuit.onTouchUp = GameQuit;
buttonQuit.sprite_index = spr_ButtonQuit;

Now, both of these buttons, created from the same object, will do two totally different things by using script_execute to call the attached script. The base obj_UIButton object can be extended to include the “fancy” selection highlight and other features. Each instance created from the root object will instantly receive these new features without having to make a new object and repeat code.

This is just one simple example. Its not my goal to show you an extensive way to use it but, rather, to simply get you thinking about how it might help you at some point in your development journey. It is one more tool waiting to be used when you need an elegant solution.

null

Leave a Reply