unity3d 可以作为协程的MonoBehaviour方法

示例

可以将三种MonoBehaviour方法制成协程。

  1. Start()

  2. OnBecameVisible()

  3. OnLevelWasLoaded()

例如,这可用于创建仅在摄像机可见对象时执行的脚本。

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