代码示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneCtrl : MonoBehaviour
{
private void Start()
{
//开启协程
StartCoroutine(Test1());
StartCoroutine("Test2");
}
private IEnumerator Test1()
{
Debug.Log("协程Test1 准备执行");
yield return new WaitForSeconds(2.0f);
Debug.Log("协程Test1 执行完毕");
}
private IEnumerator Test2()
{
Debug.Log("协程Test2 准备执行");
yield return new WaitForSeconds(5.0f);
Debug.Log("协程Test2 执行完毕");
}
private void Update()
{
if (Input.GetKeyUp(KeyCode.S))
{
//终止全部协程
StopAllCoroutines();
}
if (Input.GetKeyUp(KeyCode.D))
{
StopCoroutine("Test2");
}
}
}
一、开启协程
这里我们创建一个脚本SceneCtrl.cs,并将其挂载到主摄像机中。开启协程有两种传递参数的方法,如上面的代码所示:
StartCoroutine(Test1());
StartCoroutine("Test2");
二、在协程中等待
如代码所示:
yield return new WaitForSeconds(2.0f);
这将会延迟两秒在执行后面的Debug。
三、终止协程
1.使用StopAllCoroutines()终止协程,将会把所有的协程都终止掉。
2.单个终止。
若是使用StopCoroutine(“Test2”)终止协程,那就必须配套使用,在开启Test2协程的时候必须使用StartCoroutine(“Test2”)的方法开启,而不能用 StartCoroutine(Test2())的方法开启,如果使用后者,则将会导致StopCoroutine(“Test2”)。无法执行。