【问题标题】:Unity: how to make the update() function wait a few secondsUnity:如何让 update() 函数等待几秒钟
【发布时间】:2021-03-28 02:49:48
【问题描述】:

所以我试图让我的 update() 函数在玩家每次按下按钮“C”时等待几秒钟,因为每次当玩家按下键“c”时它都会重置对象的旋转并且我正在尝试让我的游戏等待几秒钟,因为它会使对象的一些小动画重置他的旋转值。

void Reset()
{
    Vector3 newRotation = 
    gameObject.transform.rotation.eulerAngles;

    if (Input.GetKeyDown(KeyCode.C))
    {

        x = newRotation.x;
        y = newRotation.y;
        z = newRotation.z;

        x = Mathf.Round(x);
        y = Mathf.Round(y);
        z = Mathf.Round(z);

        yield return new WaitForSeconds(1);

        print(x + " " + y + " " + z);

        for (; x >= 0; x--)
        {

            arotation.x = x;
            boxy.transform.Rotate(arotation.x, y, z);
            if (x == 0)
            {
                for (; y >= 0; y--)
                {
                    arotation.y = y;
                    boxy.transform.Rotate(arotation.x, arotation.y, z);

                    if (y == 0)
                    {
                        for (; z >= 0; z--)
                        {
                            arotation.z = z;
                            boxy.transform.Rotate(arotation.x, arotation.y, arotation.z);
                        }
                    }
                }
            }
        }
        print(x + " " + y + " " + z);
    }
}

【问题讨论】:

  • 您不能阻止Update 方法。这将冻结你的游戏。你可以尝试使用协程。
  • 你需要使用协程,所以你会得到IEnumerator Reset()而不是返回void Reset(),那样yield return new WaitForSeconds(1)实际上会等待一秒钟。请注意,调用函数将使用StartCoroutine(Reset()); 而不仅仅是Reset(); docs.unity3d.com/Manual/Coroutines.html

标签: c# unity3d time


【解决方案1】:

您应该添加返回类型重置方法。例如

IEnumerator Reset() {
   // your process
   yield return new WaitForSeconds(1);
  // continue process
} 

在使用该功能时需要使用startcoroutine方法。

void Update() {
     StartCoroutine("Reset");
}

【讨论】:

    【解决方案2】:

    使用这个:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class move : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            StartCoroutine("Reset");
        }
    
        // Update is called once per frame
        void Update()
        {
        }
        IEnumerator Reset()
        {
            //Put your code before waiting here
    
            yield return new WaitForSeconds(1);
    
            //Put code after waiting here
    
            //You can put more yield return new WaitForSeconds(1); in one coroutine
    
            StartCoroutine("Reset");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 2012-10-03
      • 2021-07-07
      • 2017-07-20
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      相关资源
      最近更新 更多