当前位置:   article > 正文

update 里面的协程处理_update is called once per frame

update is called once per frame
// Update is called once per frame
void Update () {
        if(Input.GetKeyDown(KeyCode.Space))
            StartCoroutine(test());


}


    IEnumerator test()
    {
        int cnt = 0;
        while (true)


        {


            yield return new WaitForSeconds(0.5f);
            Debug.Log(cnt++);
        }
    }

}

这里的cnt,每个协程是互不干扰的。。。。



   public int m = 0;
void Start () {
        m = 0;
}

// Update is called once per frame
void Update () {
        if (Input.GetKeyDown(KeyCode.A)) {
            m++;
            StartCoroutine(test(m));
        }
}
    int a = 0;
    IEnumerator test(int  m) {


    
        while (true) {
            yield return new WaitForSeconds(0.8f);
            Debug.Log(a++ +"   "+m);
        }
    }
}

 这里是多个协程处理同一个变量,变量会一直累加下去



协程不是线程,也不是异步执行的。协程和 MonoBehaviour 的 Update函数一样也是在MainThread中执行的

协程是一个分部执行,遇到条件(yield return 语句)会挂起,直到条件满足才会被唤醒继续执行后面的代码。

        Unity在每一帧(Frame)都会去处理对象上的协程。Unity主要是在Update后去处理协程


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/48074
推荐阅读
相关标签
  

闽ICP备14008679号