简体   繁体   English

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

[英]How to change variable for a certain period of time

How to change a variable in Unity3D just for 5 seconds or until a certain event? 如何在Unity3D中更改变量仅持续5秒或直到某个事件? For example, changing velocity: 例如,改变速度:

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

Since A is pressed, object goes up all the time. 由于A被按下,物体一直在上升。 How to make object go up not all the time, but every frame while A is pressed? 如何使对象不是一直上升,而是按下A时的每一帧? And when A is not pressed, object's velocity goes back to zero. 当没有按下A时,物体的速度会回到零。 I used to make it this way: 我曾经这样做过:

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

But this method is not rational and overloads CPU. 但是这种方法不合理且CPU过载。 Also, I can't use Input.GetKeyUp(KeyCode.A) or "else" statement as a trigger. 另外,我不能使用Input.GetKeyUp(KeyCode.A)或“else”语句作为触发器。

I would use x as a property like if it was speed. 我会使用x作为属性,如果它是速度。 I'll just psudeo code it.. On your Update() for each frame you only care about Speed in this case so you just call it. 我只是psudeo代码..在你的Update()每个帧你只关心速度在这种情况下所以你只需要调用它。 You don't have to constantly check for other values because those should be handled by other events. 您不必经常检查其他值,因为这些值应由其他事件处理。

Property Speed get;set;

    Void APressed()
{
     Speed = 5;
}

Void AReleased()
{
     Speed = 0;
}

Sorry I forgot the second part after 5 seconds.. You could add in something like this, If Unity supports the async keyword.. You would then update your A pressed to look like this 对不起,我在5秒后忘记了第二部分..你可以添加这样的东西,如果Unity支持async关键字..你会更新你的A按下看起来像这样

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


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

have you tried this? 你试过这个吗?

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

Take a look at CoRoutines in Unity/C#: http://docs.unity3d.com/Manual/Coroutines.html 在Unity / C#中查看CoRoutines: http ://docs.unity3d.com/Manual/Coroutines.html

This may do exactly what you need. 这可能正是您所需要的。 I have put some pseudo code below if I understand your issue correctly. 如果我正确理解你的问题,我在下面放了一些伪代码。

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