如何在一段时间内更改变量

How to change variable for a certain period of time

如何在 Unity3D 中更改变量仅 5 秒或直到某个事件?例如,改变速度:

void Start ()
{
    GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update ()
{
   if (Input.GetKey(KeyCode.W))
   {
       goUp ();
   }
}
public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

自从按下A后,物体一直在上升。如何让对象不是一直上升,而是在按下 A 时每一帧上升?当 A 未被按下时,物体的速度回到零。我以前是这样做的:

void Start () {
   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

void Update () {

   GetComponent<Rigidbody2D> ().velocity = Vector3.zero;

   if (Input.GetKey(KeyCode.A)) {
       goUp ();
   }

}

public void goUp() {
   GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
}

但是这个方法不合理并且重载了CPU。另外,我不能使用 Input.GetKeyUp(KeyCode.A) 或 "else" 语句作为触发器。

我会将 x 用作 属性 就像它是速度一样。我只是伪代码.. 在这种情况下,在每一帧的 Update() 上你只关心速度,所以你只需要调用它。您不必经常检查其他值,因为这些值应该由其他事件处理。

Property Speed get;set;

    Void APressed()
{
     Speed = 5;
}

Void AReleased()
{
     Speed = 0;
}

对不起,我在 5 秒后忘记了第二部分.. 您可以添加类似这样的内容,如果 Unity 支持 async 关键字。然后您可以将 A pressed 更新为如下所示

   Void APressed()
    {
         Speed = 5;
ReduceSpeedAfter5Seconds();
    }


public async Task ReduceSpeedAfter5Seconds()
{
    await Task.Delay(5000);
    Speed = 0;
}

你试过吗?

if (Input.GetKey(KeyCode.A)) {
       goUp ();
   }
else
{
    GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
}

看看 Unity/C# 中的 CoRoutines: http://docs.unity3d.com/Manual/Coroutines.html

这可能正是您所需要的。如果我正确理解你的问题,我在下面放了一些伪代码。

if (Input.GetKeyDown("a")) {
    goUp();
    StartCoroutine("ReduceSpeedAfter5Seconds");
}

IEnumerator ReduceSpeedAfter5Seconds() {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);
        yield return new WaitForSeconds(5.0f);
}