IEnumerator test1(float waitTime) {//可变参数 yield return null;//yield return表示协程暂停,将控制权交给Unity3D }
public Coroutine StartCoroutine(IEnumerator routine); public Coroutine StartCoroutine(string methodName, [DefaultValue("null")] object value);
public void StopCoroutine(string methodName); public void StopCoroutine(IEnumerator routine); //前者是使用方法名字符串,后者是使用方法的引用。 //前者可以停止第一个名字为methodName的协程;后者可以准确地停止你引用的那个协程 //第一种 StartCoroutine("DoSomething"); yield return new WaitForSeconds(2f); StopCoroutine("DoSomething"); //第二种 IEnumerator dosomething = DoSomething(); StartCoroutine(dosomething); yield return new WaitForSeconds(2f); StopCoroutine(dosomething); //错误示例:并不能停止DoSomething,开启的协程和停止的协程不是同一个引用 StartCoroutine(DoSomething()); yield return new WaitForSeconds(2f); StopCoroutine(DoSomething());
延时功能
IEnumerator test2(float waitTime) { //等待waitTime秒之后执行后续代码 yield return new WaitForSeconds(waitTime); //暂停协程直到下一次FixedUpdate时才会继续执行协程,WaitForFixedUpdate类暂停的时间取决于Unity3D的编辑器中的 TimeManager的FixedTimestep中的值 yield return new WaitForFixedUpdate(); //等到所有摄像机和GUI被渲染完成后,再恢复协程的执行 yield return new WaitForEndOfFrame(); }
IEnumerator ScreenShotPNG() { yield return new WaitForEndOfFrame(); int width = Screen.width; int height = Screen.height; Texture2D tex = new Texture2D(width,height,TextureFormat.RGB24,false); tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); byte[] bytes = tex.EncodeToPNG(); Destroy(tex); File.WriteAllBytes(Application.dataPath + "/../SaveScreen.png", bytes); }
原文:https://www.cnblogs.com/tqw1215/p/13388703.html