协程的原理与作用
Unity 协程(Coroutine)原理与用法详解_unity coroutine-CSDN博客
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NO14_coroutine : MonoBehaviour
{
Animator animator;
// Start is called before the first frame update
void Start()
{
animator = transform.GetComponent<Animator>();
//开启协程
//StartCoroutine("Grisplay");
IEnumerator ie = Grisplay();
StartCoroutine(ie);
//停止协程
//StopCoroutine("Grisplay");
StopCoroutine(ie);
//StopAllCoroutines();
}
// Update is called once per frame
void Update()
{
}
IEnumerator Grisplay()
{
//暂停几秒(协程挂起)
yield return new WaitForSeconds(2);
print("Run");
animator.Play("Gris_Run");
//等待一帧,与参数无关
yield return null;
yield return 10000;
print("no!!!");
//在帧末执行以下逻辑
}
}
协程开始与停止方式
1.
StartCoroutine("Grisplay");
StopCoroutine("Grisplay");
2.将协程对象转换为IEnumerator类型变量
IEnumerator ie = Grisplay();
StartCoroutine(ie);
StopCoroutine(ie);
注:以上两种协程开始与停止的两种方式必须配套使用不能混搭,StopAllCoroutines()可以停止所有不管任何方式开启的协程
示例1:用携程创造5个Gris,运用到协程传参和协程的嵌套调用,使所有克隆体和本体都进行Gris_Run动画
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NO14_coroutine : MonoBehaviour
{
public Animator animator;
//public int grisCount = 5;
public int grisNum = 0;
// Start is called before the first frame update
void Start()
{
//开启协程
//StartCoroutine("Grisplay");
/*IEnumerator ie = Grisplay();
StartCoroutine(ie);*/
//停止协程
//StopCoroutine("Grisplay");
//StopCoroutine(ie);
//StopAllCoroutines();
StartCoroutine("CreateGris",5);
}
// Update is called once per frame
void Update()
{
}
IEnumerator CreateGris(int grisCount)
{
print(grisCount);
StartCoroutine(Grisplay(animator));
while (true)
{
if (grisNum >= grisCount)
{
yield break;
}
GameObject g = Instantiate(animator.gameObject);
StartCoroutine(Grisplay(g.transform.GetComponent<Animator>()));
grisNum++;
yield return new WaitForSeconds(2);
}
}
IEnumerator Grisplay(Animator g)
{
//等待一帧,与参数无关
yield return null;
yield return 10000;
print("no!!!");
//暂停几秒(协程挂起)
yield return new WaitForSeconds(2);
print("Run");
g.Play("Gris_Run");
//在本帧帧末执行以下逻辑
yield return new WaitForEndOfFrame();
}
}
注:若要对协程进行传参则需要使用上面所讲的第二种开始和结束协程的方法