For my game, I need to move gameObjects and trigger sounds (audio.Play()) at set intervals that can get very fast depending on the level of the game (<1000ms).
So far, I have tried 3 timing methods. Firstly yield / StartCoroutine with WaitForSeconds:
IEnumerator SendTimerNotification()
{
while(true)
{
NotificationCenter.defaultCenter.postNotification(_soundBeatEvent);
yield return new WaitForSeconds(_bpmInMilliseconds); // <- 0.115f
}
}
secondly as above with WaitForFixedUpdate:-
IEnumerator SendTimerNotificationFixed()
{
float curTime = Time.time;
while (true)
{
if (Time.time >= curTime + _bpmInMilliseconds)
{
NotificationCenter.defaultCenter.postNotification(_soundBeatEvent);
curTime += _bpmInMilliseconds;
}
yield return new WaitForFixedUpdate();
}
}
and finally, InvokeRepeating:
InvokeRepeating("SendTimerNotification", 0, _bpmInMilliseconds);
With all instances, once the speed is less than a second, the cpu usage gets quite high. For the sake of brevity, the NotificationCenter class shown is a simple class that broadcasts notifications. Currently there is one gameObject listening for this notification and it plays its attached audioSource object when it is received.
Are there other more cpu efficient means of handling timed events in Unity that I have yet to discover (I have been trialing the package a week).
Any info on the subject is most appreciated.
Thanks,
Dave