So I made this handy little timer script which will be called from another script:
using UnityEngine;
using System.Collections;
public class Timer : MonoBehaviour {
private float StopTime = Time.time;
private bool Running = false;
public void test(float SecondsToWait){
Running = true;
StopTime = Time.time + SecondsToWait;
while(Running == true){
if(Time.time == StopTime){
Running = false;
}
}
}
}
But now I want it to return it has finished timing. Can anyone tell me how?
?? That loop will just freeze your program. It needs yield return null;
and to be in a coroutine. Beyond that, the == will always be false (time will jump from just under, to just over. Use <=
.) Why are stopTime and running globals? What if two people want to time something?
And why not just use the built-in WaitForSeconds? Or, in many cases, just the built-in Invoke
.
I’d restart with what the end result is, and look from there.
I had quite the same problem. I ended up writing a bit more generic solution. So what I did, I created a persistent gameobject to handle ‘wait & execute something’- kind of pattern. Here how it goes…
using UnityEngine;
using System.Collections;
public delegate void TimerCommand();
public class MyTimer : MonoBehaviour {
private static TimerCommand _timerCallBack;
private static float _targetTime;
private static bool _isRunning = false;
void Awake()
{
DontDestroyOnLoad(this);
}
public static void StartMyTimer(float time,TimerCommand callBack)
{
//Ensure that last StartMyTimer call has finished
if(_isRunning)
return;
_timerCallBack = callBack;
_targetTime = Time.realtimeSinceStartup+time;
_isRunning = true;
}
// Update is called once per frame
void Update ()
{
if(_isRunning && Time.realtimeSinceStartup > _targetTime)
{
_isRunning = false;
_timerCallBack();
}
}
}
So create an empty gameobject and attach the script to it. If you wish, create a prefab.
My need in this case was to tune down the volume of my background music while another short music clip was played. So here’s an example how to use this. What it does, it waits for 2 seconds and then resets the background music volume to 1.0f.
//Note the lambda expression syntax.
//Of course any method matching the delegate declared in the MyTimer will do
MyTimer.StartMyTimer(2.0f,
//the callback which is called when timer has finished
() => { audio.volume = 1.0f;});
Obviously the mytimer script can be tweaked to take multiple timed events, set up periodic ‘events’ etc. But for now, this was sufficient for my needs. Hope this helps.