Reputation: 3732
To make my game more dynamic, I have created a script in which arguments are used in order to be substituted by pre defined variables.
Upon clicking the left mouse_button, there is the code:
script_execute(scrShoot, weapon1, ammo1);
Where weapon1 and ammo1 are local variables.
The simple script 'scrShoot' is as follows:
if argument0 = 1
{
argument1 -= 0.05;
instance_create(x,y,objBullet);
}
if argument0 = 2
{
argument1 -= 0.05;
repeat(4)
{
instance_create(x,y,objBullet2);
}
}
argument0 works as expected, being successfully substituted by weapon1, however, the variable ammo1 never decreases.
When I manually write in ammo1 in place of argument1, the script works fine; decreasing by 0.05 with every click.
Other tests using scripts have lead me to believe that the problem lies with using variables to substitute arguments: strings and numbers work as you would expect.
I have encountered this problem in more than one scenario and I'm baffled that nobody else on the internet seems to have come across the same problem.
Upvotes: 0
Views: 2503
Reputation: 10794
When you pass a number as an argument to a script, you’re giving that script a copy of the number to work with. That is, the script doesn’t see that you’re passing it ammo1
– it only sees that you passed it, say, 50
. The line argument1 -= 0.05
just modifies the copy the script receives, not ammo1
itself.
This is called passing an argument by value (giving the script a copy that it can modify), as opposed to by reference (pointing the script to a variable to modify).
See: What's the difference between passing by reference vs. passing by value?
GML itself doesn’t have syntax for passing arguments by-reference, so you’re out of luck. What you can do, I believe, is pass an instance ID (like self
or other
, or the result of a call to instance_create
) to the script:
/// scrShoot()
var o = argument0;
if (o.weapon == 1) {
o.ammo -= 0.05;
instance_create(x, y, objBullet);
}
/// Your object
script_execute(scrShoot, self);
Upvotes: 3