- Home /
Time elapsed between variable change?
Everytime my character destroys an enemy, I have a variable that increases by 1.
If two successive enemy destructions (and variable increases) happen too fast (eg in less than a second), I want something to happen (eg activate a sound, or change a boolean var). I think that I should somehow use deltaTime.
How do I check how much time passed between 2 successive value changes of a variable (in this case chainHits var)?
Thanks for reading :-)
Answer by Ray-Pendergraph · Dec 18, 2010 at 01:14 PM
If you are using C# and are using properties, you can just capture a DateTime inside the property setter, or as part of the property changed event. Then every time it's set just see if the last set was before a certain time. If it is, do something.
If you are not using C#, this (data encapsulation) is just one of the great reasons you should consider the switch ;-). Seriously, if you are not and are using UnityScript you will need to encapsulate the access of that data inside of a method (like a setter) and do what I described above. Just exposing a public variable will not do this.
The last and really nasty, not elegant solution would be to note the value in a second variable, then periodically, perhaps in Update or LateUpdate see if the original is different note the time.
if (variable != shadowVariable)
{
//is the timespan since the last noted change less than my
//predefined period.
if (currentTime - lastChangedTime < predefinedTimePeriod)
{
DoThing();
}
shadowVariable = variable;
lastChangedTime = currentTime;
}
That's psuedocode of course, but hopefully you get the idea.
thank you Ray, but I don't quite understand what exactly I must do. I think that this is the basic idea that I try to implement. $$anonymous$$aybe it's because I am a bit tired. I'll look into it for the next hours though. Thanks anyway.
$$anonymous$$y guess is that you are using UnityScript? If so the code above should be really close to what you need where 'variable' is the main variable, 'shadowvariabl'e is a variable with the same type and currentTime will actually be var currentTime will be a System.DateTime assigned like this 'currentTime = DateTime.Now; DoThing(); is a method that get's called when successive updates are sufficiently close together... that's pretty much it.
Thanks again Ray, as you said, that was pretty much it, only I had to take into account the order in which things happen in my script.
Your answer
Follow this Question
Related Questions
How do I set a max limit for my health value? 4 Answers
Time of day script not working 2 Answers
Positive to negative not working? 1 Answer
Make a change every 0.02 seconds precise 1 Answer
Static Variable Doesn't Change ? 0 Answers