一、协同程序
协同程序:能暂停执行,暂停后立即返回,直到中断指令完成后继续执行的函数,类似一个子线程单独出来处理一些问题,性能开销较小,若在脚本运行过程中,需要额外的执行一些其他的代码,这个时候就可以将“其他的代码”以协程的形式来运行
普通程序都是自上而下的执行过程,协同程序就相当于给予其中一些语句开开辟捷径单独执行
- 只有在继承了“MonoBehaviour”这个类的子类中才能使用相关的协程方法
- 在一个MonoBehaviour提供的主线程里也只能有一个处于运行状态的协程
协同程序很容易写出各种BUG
使用方法:
IEnumerator Print3()
{
yield return new WaitForSeconds(5);
Debug.Log("33333");
}
参数说明:
- IEnumerator:协同程序的返回值类型
- yield return:协同程序返回内容,必须要有至少一个返回
- new WaitForSeconds:实例化一个对象,等待多少秒后继续执行
开启与关闭协同程序
- StartCoroutine(string):开始执行协程string
- StopCoroutine(string):停止执行协程string
代码和效果如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
Debug.Log("11111111");
Debug.Log("22222222");
StartCoroutine("Print3");
Debug.Log("44444444");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
StopCoroutine("Print3"); //按K键停止协程"Print3"
}
}
IEnumerator Print3()
{
yield return new WaitForSeconds(5);
Debug.Log("33333");
yield return new WaitForSeconds(5);
Debug.Log("55555");
}
}