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!

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);
	}
}