yield return

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaitTest : MonoBehaviour {

    public int frame;

    void Start () {
        StartCoroutine(WaitWhileTest());
        StartCoroutine(WaitUntilTest());
        StartCoroutine(WaitForSecondsRealtimeTest());
        StartCoroutine(WaitForSecondsTest());
        StartCoroutine(WaitForFixedUpdateTest());
    }

    IEnumerator WaitWhileTest()
    {
        Debug.Log("Begin WaitWhileTest()");
        //条件成立时会一直等待
        yield return new WaitWhile(() => frame < 10);
        Debug.Log("End WaitWhileTest()");
    }

    IEnumerator WaitUntilTest()
    {
        Debug.Log("Begin WaitUntilTest()");
        //条件不成立时会一直等待
        yield return new WaitUntil(() => frame >= 10);
        Debug.Log("End WaitUntilTest()");
    }

    IEnumerator WaitForSecondsRealtimeTest()
    {
        print("Begin WaitForSecondsRealtimeTest, " + Time.time);
        //等待5秒, 不受Time.timeScale影响
        yield return new WaitForSecondsRealtime(5);
        print("End WaitForSecondsRealtimeTest, " + Time.time);
    }

    IEnumerator WaitForSecondsTest()
    {
        print("Begin WaitForSecondsTest, " + Time.time);
        //等待5秒, 受Time.timeScale影响
        yield return new WaitForSeconds(5);
        print("End WaitForSecondsTest, " + Time.time);
    }

    IEnumerator WaitForFixedUpdateTest()
    {
        print("Begin WaitForFixedUpdateTest");
        //等待FixedUpdate()执行完毕
        yield return new WaitForFixedUpdate();
        print("End WaitForFixedUpdateTest");
    }

    IEnumerator WaitForEndOfFrameTest()
    {
        print("Begin WaitForEndOfFrameTest");
        //等待当前帧执行完毕
        //例如,截屏时需要等待当前帧渲染完后再截。
        yield return new WaitForEndOfFrame();
        print("End WaitForEndOfFrameTest");
    }
}

yield break;//直接结束协程

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号