- Home /
is it cheaper to run timer another, or refer to other timer?
Hey everyone. Thanks for reading my question. Have multiple scrips running timers that could all line up and my question is: Would it be faster to have them all run their own timer, or refer to another scripts timer once a frame.
Something like this:
public int framesBetweenCheck = 50;
private int framesBetweenCheckTemp = 0;
private void FixedUpdate () {
framesBetweenCheckTemp++;
if (framesBetweenCheckTemp >= framesBetweenCheck) {
// Do something;
}
framesBetweenCheckTemp = 0;
}
or something like this:
private int framesBetweenCheckTemp = 0;
public GameObject _timer;
private TimerScript _timerScript;
private void Start () {
_timer = GameObject.Find ("Timer");
_timerScript = _timer.GetComponent<TimerScript> ();
}
private void FixedUpdate () {
if (_timerScript.temp < 1) {
// Do something
}
}
I could be running this timer on a lot of scripts, so the cost or benifit would be amplified. Thanks again for reading my question!
Just a note on timers, generally you want to compare real time values, rather than the number of time-steps. This has both the advantage of saving a read/write operation of a variable and has a much larger accuracy, since the time between FixedUpdate
calls is never guaranteed.
Answer by SkaredCreations · Mar 22, 2014 at 02:53 AM
I think it's up to what's your need from the timer script, because if you use a single component to manage this then you know that the counter is shared across all the objects that is checking for it.
If you're fine with having a shared counter, then I'd suggest something like the second (a TimerScript) but using a delegate callback instead of check the value in each FixedUpdate cycle, for example:
TimerScript:
using UnityEngine;
using System.Collections;
public class TimerScript : MonoBehaviour {
public System.Action callback;
public int framesBetweenCheck = 50;
private int framesBetweenCheckTemp = 0;
void FixedUpdate () {
framesBetweenCheckTemp++;
if (framesBetweenCheckTemp >= framesBetweenCheck) {
// Do callback
if (callback != null)
callback();
framesBetweenCheckTemp = 0;
}
}
}
Your other script:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Start () {
GameObject _timer = GameObject.Find ("Timer");
TimerScript timerScript = _timer.GetComponent<TimerScript> ();
timerScript.callback += OnTimerElapsed;
}
void OnTimerElapsed () {
// Do something
Debug.Log("OnTimerElapsed >> " + name);
}
}
Thanks man! I don't really understand what a callback is though. What is the difference between a callback and just a traditional check?
Your answer
Follow this Question
Related Questions
timer problem 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# countdown timer 9 Answers