Unity 协程

生命周期表:
在这里插入图片描述
协程:

/// <summary>
///  unity的协程毫无疑问是个非常棒的设计,让我们能够非常方便的编写类似“异步”代码,提高开发效率。

//在开发过程中用到最多的当属yield return null,yield return new WaitForSeconds 和 yield return new WaitForEndOfFrame了;

//WaitForEndOfFrame,顾名思义是在等到本帧的帧末进行在进行处理,这个问题不大,比较不容易搞错。

//yield return null表示暂缓一帧,在下一帧接着往下处理,也有人习惯写成yield return 0或者yield return 1,于是误区就随之而来了,很多同学误认为yield return后面的数字表示的是帧率,比如yield return 10,表示的是延缓10帧再处理,实则不然,yield return num;的写法其实后面的数字是不起作用的,不管为多少,表示都是在下一帧接着处理。

//yield return new WaitForSeconds,这个要注意的是1·实际时间等于给定的时间乘以Time.timeScale的值。2·触发间隔一定大等于1中计算出的实际时间,而且误差的大小取决于帧率,因为它是在每帧处理协程的时候去计算时间间隔是否满足条件,如果满足则继续执行。例如,当帧率为5的情况下,一帧的时间为200ms,这时即使时间参数再小,最快也要200ms之后才能继续执行剩余部分。

/// </summary>
/// </summary>
public class testCoroutine : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        //StartCoroutine("Coroutine1",0);// 停止这个动作中名为methodName的所有协同程序。请注意只有StartCoroutine使用一个字符串方法名时才能用StopCoroutine停用之.


        //StartCoroutine(Cornutine2());
        //StartCoroutine(Coroutine3());
        //StartCoroutine(Coroutine4());
        StartCoroutine(Coroutine5());// 5  2  3  4

        MainForExample();
    }

    // Update is called once per frame
    void Update() {

        if (Input.GetKeyDown(KeyCode.Space)) {
            Debug.Log("Space");
            StopCoroutine("Coroutine1");
        }
    }

    int k = 0;
    IEnumerator Coroutine1() {

        while (true) {
            k++;
            Debug.Log(k);
            yield return null;
            Debug.Log("Coroutine1 function");
        }

    }

    IEnumerator Cornutine2() {

        yield return null;
        Debug.Log("null function");
    }

    IEnumerator Coroutine3() {

        yield return new WaitForEndOfFrame();
        Debug.Log("WaitForEndOfFrame function");
    }

    IEnumerator Coroutine4() {

        yield return new WaitForSeconds(3);
        Debug.Log("WaitForSeconds function");
    }

    IEnumerator Coroutine5() {

        yield return new WaitForFixedUpdate();
        Debug.Log("WaitForFixedUpdate function");
    }




    public static bool onOff = false;

    public static IEnumerable ForExample() {
        yield return "1";  // 第一次调用时执行
        yield return "2";  // 第二次调用时执行
        if (onOff)            // 第三次调用时执行
        {
            // 执行 yield break 之后不再执行下面语句
            yield break;
        }
        // 否则,onOff为 false
        yield return "3";  // 第四次调用时执行
        yield return "4";  // 第五次调用时执行
    }

    static void MainForExample() {
        foreach (string s in ForExample())

            Debug.Log(s);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值