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