繁体   English   中英

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

[英]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作为属性,如果它是速度。 我只是psudeo代码..在你的Update()每个帧你只关心速度在这种情况下所以你只需要调用它。 您不必经常检查其他值,因为这些值应由其他事件处理。

Property Speed get;set;

    Void APressed()
{
     Speed = 5;
}

Void AReleased()
{
     Speed = 0;
}

对不起,我在5秒后忘记了第二部分..你可以添加这样的东西,如果Unity支持async关键字..你会更新你的A按下看起来像这样

   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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM