Coroutine
类似多线程的一种操纵,是一个协程函数
协程方法开启后,会继续运行下面的代码,不会等协程方法运行结束才继续执行
1.返回值是IEnumerator
2.返回参数的时候使用yield return null/0;
3.携程方法的调用StartCoroutine(调用的方法())
void Start()
{
Debug.Log(1);
StartCoroutine(ChageColor());
Debug.Log(2);
}
IEnumerator ChageColor()
{
Debug.Log(3);
yield return new WaitForSeconds(3); //暂停3s
GameObject go = GameObject.Find("Quad");
go.GetComponent<MeshRenderer>().material.color = Color.black;
Debug.Log(4);
yield return null;
}
使用协程完成物体颜色的渐变
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(FadeChangeColor());
}
}
IEnumerator FadeChangeColor()
{
Debug.Log(5);
while (true)
{
GameObject go = GameObject.Find("Quad");
Color color = go.GetComponent<MeshRenderer>().material.color;
//使得颜色渐变的函数Lerp
Color newColor = Color.Lerp(color, Color.blue, 0.02f);
go.GetComponent<MeshRenderer>().material.color = newColor;
yield return new WaitForSeconds(0.02f);
Debug.Log(newColor.b);
if(Mathf.Abs(Color.blue.b + newColor.b) >= 1.9f)
{
break;
}
}
yield return null;
}
StopCoroutine
StopAllCoroutines
前者停止指定的协程,后者是停止所有的协程
之前的StartCoroutine是什么形式,StopCoroutine也要什么形式
StartCoroutine("ChageColor");
StopCoroutine("ChageColor");
private IEnumerator ie;
if (Input.GetKeyDown(KeyCode.A))
{
ie = FadeChangeColor();
StartCoroutine(ie);
}
if (Input.GetKeyDown(KeyCode.B))
{
StopCoroutine(ie);
Debug.Log("stop");
}