【问题标题】:unity run function from coroutine来自协程的统一运行功能
【发布时间】:2019-06-26 17:39:22
【问题描述】:

嗨,为什么这不起作用 我正在尝试从函数运行的 cororotine 旋转游戏对象,但如果我将旋转放入更新中,它运行良好我很困惑感谢任何帮助

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

public class waitthendosomthing : MonoBehaviour
{
    public bool beingHandled = true; //  bool
    void Update()
    {
        //transform.Rotate(6, 0, 0);// this runs 
        if (beingHandled == true )
        {
            StartCoroutine(HandleIt());// run function
        }

    }

    void rotateit()
    {
        transform.Rotate(6, 0, 0);// this dosnt run
        print("running this function");
    }

    IEnumerator HandleIt()
    {
            beingHandled = false;
            print("BeingHandled is off");
            rotateit();
            //transform.Rotate(6, 0, 0); // or this
            yield return new WaitForSeconds(3.1f);
            //transform.Rotate(0, 0, 0); // or this
            yield return new WaitForSeconds(3.1f);
            beingHandled = true;
            print("BeingHandled is on");
    }
}

【问题讨论】:

    标签: unity3d coroutine


    【解决方案1】:

    它在更新中起作用的原因是因为更新是在每个帧上调用的。所以每一帧立方体都会旋转6度并按预期连续旋转

    协程只执行两次旋转,一次旋转到 6 度,然后在 3.1 秒后返回到 0 度。

    如果您想在 co 例程中进行轮换,则必须以不同的方式实现它:

    例如:

            double time = 0.0f;
    
            while (time < 3.1f)
            {
                time += Time.deltaTime;
                rotateit();
                yield return null;
            }
    

    这将使立方体连续旋转 3.1 秒,然后停止。

    【讨论】:

    • 一般来说你应该考虑使用例如transform.Rotate(6 * Time.deltaTime, 0, 0); 为了不旋转固定 6 度/帧而是 6 度/秒。
    猜你喜欢
    • 2016-01-16
    • 2014-10-29
    • 1970-01-01
    • 2017-05-16
    • 2023-02-07
    • 2022-11-07
    • 2022-08-11
    • 2013-01-03
    相关资源
    最近更新 更多