yield return

作者:追风剑情 发布于:2019-5-28 10:31 分类:Unity3d

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class WaitTest : MonoBehaviour {
  6.  
  7. public int frame;
  8.  
  9. void Start () {
  10. StartCoroutine(WaitWhileTest());
  11. StartCoroutine(WaitUntilTest());
  12. StartCoroutine(WaitForSecondsRealtimeTest());
  13. StartCoroutine(WaitForSecondsTest());
  14. StartCoroutine(WaitForFixedUpdateTest());
  15. }
  16.  
  17. IEnumerator WaitWhileTest()
  18. {
  19. Debug.Log("Begin WaitWhileTest()");
  20. //条件成立时会一直等待
  21. yield return new WaitWhile(() => frame < 10);
  22. Debug.Log("End WaitWhileTest()");
  23. }
  24.  
  25. IEnumerator WaitUntilTest()
  26. {
  27. Debug.Log("Begin WaitUntilTest()");
  28. //条件不成立时会一直等待
  29. yield return new WaitUntil(() => frame >= 10);
  30. Debug.Log("End WaitUntilTest()");
  31. }
  32.  
  33. IEnumerator WaitForSecondsRealtimeTest()
  34. {
  35. print("Begin WaitForSecondsRealtimeTest, " + Time.time);
  36. //等待5秒, 不受Time.timeScale影响
  37. yield return new WaitForSecondsRealtime(5);
  38. print("End WaitForSecondsRealtimeTest, " + Time.time);
  39. }
  40.  
  41. IEnumerator WaitForSecondsTest()
  42. {
  43. print("Begin WaitForSecondsTest, " + Time.time);
  44. //等待5秒, 受Time.timeScale影响
  45. yield return new WaitForSeconds(5);
  46. print("End WaitForSecondsTest, " + Time.time);
  47. }
  48.  
  49. IEnumerator WaitForFixedUpdateTest()
  50. {
  51. print("Begin WaitForFixedUpdateTest");
  52. //等待FixedUpdate()执行完毕
  53. yield return new WaitForFixedUpdate();
  54. print("End WaitForFixedUpdateTest");
  55. }
  56.  
  57. IEnumerator WaitForEndOfFrameTest()
  58. {
  59. print("Begin WaitForEndOfFrameTest");
  60. //等待当前帧执行完毕
  61. //例如,截屏时需要等待当前帧渲染完后再截。
  62. yield return new WaitForEndOfFrame();
  63. print("End WaitForEndOfFrameTest");
  64. }
  65. }

yield break;//直接结束协程

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号