废话不多说,下面就用一个简单的显示指引案件的例子来展示如何用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来开始并行函数的运行了。