I want to split heavy job in Update()
. Currently I am using StopWatch
for this.
The problem is several relatively independent GameObject
s that needs to have Update()
limited, therefore I am looking for something like Time.realtimeSinceUpdateStarts
.
I don’t know which of GameObject
will run its Update
first to measure this time myself. I don’t want to run all GameObject
Update
s via some manager and while priority queue might be cool at some point, for the moment I am looking for a very simple method to discard all updates if either of them takes too long.
Ideas?
I understand the Unity runs Update
method for each active object, which is the first object, perhaps I just hook my StopWatch
to it?
LetsTestThisUpdateTrackerThing.cs:
using UnityEngine;
public class LetsTestThisUpdateTrackerThing : MonoBehaviour
{
[SerializeField] int _workload = 10000;
[SerializeField][Range(0,60)] int _msBudget = 30;
void Update ()
{
for( int i=0 ; i<_workload ; i++ )
if( UpdateTracker.watch.ElapsedMilliseconds<_msBudget )
Work();
}
void Work ()
{
for( int i=0 ; i<1000 ; i++ )
{
float f = Mathf.Sqrt( Random.Range(1,float.MaxValue) );
}
}
}
UpdateTracker.cs:
using UnityEngine;
[DefaultExecutionOrder(-1000)]
public class UpdateTracker : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod( RuntimeInitializeLoadType.BeforeSceneLoad )]
static void _InitializeType () => DontDestroyOnLoad( new GameObject(nameof(UpdateTracker)).AddComponent<UpdateTracker>().gameObject );
public static System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
void Update () => watch.Restart();
}
What is wrong with Time.deltaTime
?
It measures the time past in a frame and is heavily used everywhere in Unity