廢話不多說,下面就用一個簡單的顯示指引案件的例子來展示如何用coroutine來暫停程序的執行
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class TextTriggered : MonoBehaviour
{public GameObject TextObject;// Start is called before the first frame updatevoid Start(){TextObject.SetActive(false);}private void OnTriggerEnter(Collider other){// debug// Debug.Log("the player triggered");// if the player is nearby, show the message on the screenif(other.gameObject.tag == "Player"){TextObject.SetActive(true);StartCoroutine(waitForSec());}}IEnumerator waitForSec(){yield return new WaitForSeconds(2);Debug.Log("we will destroy the object");TextObject.SetActive(false);}
}
類似單片機設置timer,在使用coroutine時要先定義一個 返回類型為IEnumerator的函數,注意是IEnumerator而不是IEnumerable,在該函數中,利用WaitForSeconds來計時。需要注意的是計時從這一幀結束開始,所以在幀時間很長的時候可能會有實際經過時間大于設置的值的問題。
接著就可以在任意函數中插入,StartCoroutine來開始并行函數的運行了。