- Home /
Member variables returning to 0
Hi there,
I'm trying to create some classes and static functions which will return values after a certain period of time for me. I've managed to get it working, however some of the variables aren't necessarily defined by the arguments passed through to the function, and so I need to use static vars for them. While this works, it means that I'm unable to ever call the functions more than once because these variables only ever have one instance. What I'm trying to do instead is to have these variables declared as member variables for the functions. This is my code:
static function Intf (val : int, time : float) : int {
var timer : float;
timer += Time.deltaTime;
timer = Mathf.Clamp(timer, 0, time);
if (timer == time) {
return inst;
} else {
inst = val;
return val;
}
return;
}
However, unfortunately, timer continuously returns to 0 because of the way it is declared. I know that this is because the compiler is continuously redeclaring the variable with a value of 0 at this line: var timer : float;
but I'm not sure of the best way in which to counter this effect.
Any help on better ways to do these sorts of functions, etc. from people who've successfully done them before would be much appreciated. After all, how do we ever learn if not through our mistakes?
Sorry if I wasn't clear enough!
Thanks very much,
Klep :)
What if you make timer global and pass it to the function as parameter.
I may not fully understand and be way off on my answer and I apologize, but I defined the timer as a static variable in a class. Then ran your function in an object's update function and the conditional was true after the designated amount of time. Is that what you were trying to do?
You mean like so?
static var timer : float;
static function Intf (val : int, time : float) : int {
timer += Time.deltaTime;
timer = $$anonymous$$athf.Clamp(timer, 0, time);
if (timer == time) {
return inst;
} else {
inst = val;
return val;
}
return;
}
Yes, I have already tried this, and despite it working, it won't allow me to do things like this in say another script:
var foo : int;
var foobar : int;
function Update () {
foo = Log.Intf(Time.time, 9);
foobar = Log.Intf(Time.time, 40);
}
This will cause either one or both of those calls to screw up. Even if this isn't a great example of this sort of static function, I'm trying to start small to learn how to do them properly. :)
Why do you need it static? Why don't you make a normal function and call with a message?
Exactly.
I see what you are trying to do. $$anonymous$$aybe you can add a third parameter like an id number. So each time you run a new function, it will have a new id number. The timer static variable could become an array, and when the I d number is greater than the length $$anonymous$$us 1 of the array then you can add an entry. $$anonymous$$aybe?