unity3d Coroutines MonoBehaviour methods that can be Coroutines


Example

There are three MonoBehaviour methods that can be made coroutines.

  1. Start()
  2. OnBecameVisible()
  3. OnLevelWasLoaded()

This can be used to create, for example, scripts that execute only when the object is visible to a camera.

using UnityEngine;
using System.Collections;

public class RotateObject : MonoBehaviour
{
    IEnumerator OnBecameVisible()
    {
        var tr = GetComponent<Transform>();
        while (true)
        {
            tr.Rotate(new Vector3(0, 180f * Time.deltaTime));
            yield return null;
        }
    }
    
    void OnBecameInvisible()
    {
        StopAllCoroutines();
    }
}