I'm sure this is amazingly simple, but can't for the life of me find the answer. I'm trying to write a function that will take three arguments, do some arithmetic on them, then update their values. But I have a slew of the sets of three variables and am trying to pass them all through the same function.
function StatUpdater (stat, statnext, stattotal) {
if (stat = 0) {
stat = do some math;
statnext = some more math;
stattotal = yet more;
}
}
What am I missing to then get those values back onto the original parameters, like if I put
Not sure the JavaScript equivalent (edit: turns out there isn't one unless you write a class wrapper for your data), but what you're looking for is the ref or out keyword. In essence, those keywords allow you to pass value types "by reference" so that when you update them in a function, you're updating the original instance of the variable and not a copy.
In C#:
void Whatever( ref float a, ref float b, ref float c )
{
// whatever
}
Usage:
Whatever( ref a, ref b, ref c );
Whatever( ref a, ref b, ref c );
As the answer stated above, you need to use pass by reference.
Primitive types (ints, floats and such) are passed by value. You are modifying a copy of the original variable in the memory.
Classes, however, are passed by reference to functions. When you access them in the function, you are accessing the original memory space of the class. So wrap up your stats in a class and pass it to the function. Though if you are doing C# and only changing a few values, using ref could be a better way.
class Stats {
public var health;
public var strength;
}
class Test extends MonoBehaviour
{
public function Start()
{
s:Stats = new Stats();
s.health = 100;
ChangeHealth(s);
Debug.Log(s.health);
}
public function ChangeHealth(s:Stats)
{
s.health = 0;
}
}
Javascript has no ability to declare reference variables in functions. The only way to pass by reference at the moment is to make a class, since classes are always passed by reference.