• Unity3d 协程的注意问题(新手须注意,老手须加勉)


    关于unity3d的协程,非常的好用,比如等待几秒执行,等待下一帧执行等!

    但是也有潜在的问题:

    1.协程是单线程的,在主线程中完成

    2.如果发现yield, 那么这一帧会结束,那么等下一帧调用此脚本的时候继续执行!

    如果同一个协程方法被两个方法在相对短的时间内都进行调用,那么就会出现逻辑上的错误!这个时候需要用锁来锁定!

    我举例如下:

    using UnityEngine;
    using System.Collections;

    public class YieldScpipt : MonoBehaviour {

        // Use this for initialization
        void Start () {
        }
        // Update is called once per frame
        void Update () {
        }

        public void RunContinue()
        {
            StartCoroutine(run());
        }

        IEnumerator run()
        {
            print("1");
            //yield return 0;
            print("2");
            //yield return 0;
            print("3");
            yield return 0;
        }
    }

    在另一个类中用Test方法进行调用

    public class Test : MonoBehaviour {

        public YieldScpipt ys;
        // Use this for initialization
        void Start () {
         for(int i=0;i<3;i++)
         {
             ys.RunContinue();
         }
        }
        // Update is called once per frame
        void Update () {
        }
    }

    那么会打印如下:1,2,3,1,2,3.。。。预期的顺序

    如果把注释去掉

      IEnumerator run()
        {
            print("1");
            yield return 0;
            print("2");
            yield return 0;
            print("3");
            yield return 0;
        }
    那么打印的顺序就不能保证了,这就是我遇到的问题!

    当然,我不是用for循环这样引起的,我是不经意间写错了逻辑,导致在很短的时间内,这个方法被两次或者多次调用,导致了逻辑错误!

    有什么问题请指出!欢迎与广州老龙联系!

  • 相关阅读:
    查看当前系统的shell
    xargs命令,作用雷同|
    shell 行末尾的&含义
    apt-get 安装及卸载,dpkg查询安装文件
    Linux: mv and cp 拷贝不包含目录
    windows下远程连接ubunut
    Linux 清空屏幕
    PageHelper的一些属性设置
    HttpServletRequest
    铁电RAM为何比串行SRAM更好
  • 原文地址:https://www.cnblogs.com/alongu3d/p/5318189.html
Copyright © 2020-2023  润新知