- Home /
InvokeRepeating VS Coroutines [Performance]
Hello everyone.
I was wondering, what is better to use InvokeRepeating or Coroutines? I want to optimize my scripts and instead of calling stuff every frame per seconds inside the Update() function only call the specific function for example every 0.25f seconds. So I decided to use either InvokeRepeating or Coroutines. But I don't know what is better in terms of performance. I wrote couple of simple script. Which example is more optimized?
InvokeRepeating:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraReposition : MonoBehaviour {
[SerializeField] private Camera[] cameras;
[SerializeField] private Transform pos;
public bool forceRePosition;
void Start ()
{
InvokeRepeating("ForceRePosition", 0f, 0.2f);
}
void ForceRePosition ()
{
if (!forceRePosition) return;
cameras[0].gameObject.transform.position = pos.position;
cameras[1].gameObject.transform.position = pos.position;
}
}
Coroutines:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraReposition : MonoBehaviour {
[SerializeField] private Camera[] cameras;
[SerializeField] private Transform pos;
[SerializeField] private float WaitTime = 0.2f;
public bool forceRePosition;
void Start ()
{
StartCoroutine(ForceRePosition(WaitTime));
}
IEnumerator ForceRePosition (float waitTime)
{
while (forceRePosition)
{
yield return new WaitForSeconds(waitTime);
RePosition();
}
}
public void RePosition ()
{
cameras[0].gameObject.transform.position = pos.position;
cameras[1].gameObject.transform.position = pos.position;
}
}
Answer by TheSOULDev · Sep 24, 2017 at 03:49 PM
While invoke repeating is slightly better than coroutines for something static, you should use a coroutine to control a state machine instead so you have as few function calls creating garbage as you can.
Your answer
Follow this Question
Related Questions
Any costs I should know about associated with InvokeRepeating? 1 Answer
Fire and forget coroutines 1 Answer
Coroutine impact on frame rate 0 Answers