unity学习笔记-协程启动停止和API

StartCoroutine   启动协程。

可以使用 yield 语句,随时暂停协程的执行。

要将协程设置为运行状态,必须使用 StartCoroutine 函数

脚本禁用后再激活或者依附对象激活后都可以触发

官方手册链接      UnityEngine.WaitForEndOfFrame - Unity 脚本 API    协程 - Unity 手册

启用方式
        StartCoroutine(Test_00());
        StartCoroutine("Test_01");
        StartCoroutine(Test_02(5, 9));

============================================================

    private IEnumerator Test_00()

    private IEnumerator Test_01()

    private IEnumerator Test_02(int a, int b)

停止协程

//停止指定的协程用这个
StopCoroutine("Test_01");
//这个是停止当前脚本的所有协程
StopAllCoroutines();

函数一 、WaitForSeconds

     代码来自官方手册

官方描述:使用缩放时间将协程执行暂停指定的秒数。

using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour
{
    void Start()
    {
        //启动我们在下面定义的名为ExampleCoroutine的协程。
        StartCoroutine(ExampleCoroutine());
    }

    IEnumerator ExampleCoroutine()
    {
        //打印函数第一次调用的时间。
        Debug.Log("Started Coroutine at timestamp : " + Time.time);

        //生成一个等待5秒的yield指令。
        yield return new WaitForSeconds(5);

        //等待5秒后再次打印时间。
        Debug.Log("Finished Coroutine at timestamp : " + Time.time);
    }
}

函数二、WaitForSecondsRealtime

用法跟上面那个差不多,时间间隔比上面的短一点点

官方描述:使用未缩放时间将协同程序执行暂停指定的秒数。

using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        print(Time.time);
        yield return new WaitForSecondsRealtime(5);
        print(Time.time);
    }
}

函数三、WaitUntil

官方描述:暂停协程执行,直到提供的委托评估为 /true/。

WaitUntil(Func<bool> predicate);        用的时候照着写WaitUntil(()=》变量)

如yield return new WaitUntil(() => b);   可以写一个bool变量或者判断条件

using UnityEngine;
using System.Collections;

public class WaitUntilExample : MonoBehaviour
{
    public int frame;

    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        Debug.Log("Waiting for princess to be rescued...");
        //WaitUntil(() => frame >= 10)为true时,继续执行。
        yield return new WaitUntil(() => frame >= 10);
        Debug.Log("Princess was rescued!");
    }

    void Update()
    {
        if (frame <= 10)
        {
            Debug.Log("Frame: " + frame);
            frame++;
        }
    }
}

函数四、WaitWhile

官方描述:暂停协程执行,直到提供的委托评估为 /false/。

同上

using UnityEngine;
using System.Collections;

public class WaitWhileExample : MonoBehaviour
{
    public int frame;

    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        Debug.Log("Waiting for prince/princess to rescue me...");
        //条件为false时,才会继续执行下一句
        yield return new WaitWhile(() => frame < 10);
        Debug.Log("Finally I have been rescued!");
    }

    void Update()
    {
        if (frame <= 10)
        {
            Debug.Log("Frame: " + frame);
            frame++;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_73841296/article/details/131183469