可以将三种MonoBehaviour方法制成协程。
Start()
OnBecameVisible()
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(); } }