How to change a variable for a specific period of time

How can I change a variable in Unity3D for only 5 seconds or until a certain event? For example, changing the speed:

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, the object is constantly growing. How do I make the object go up not all the time, but every frame when A is pressed? And when A is not pressed, the object's speed returns to zero. I did it like this:

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 the CPU. Also, I cannot use the Input.GetKeyUp (KeyCode.A) or "else" statement as a trigger.

+3


source to share


3 answers


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

It might do exactly what you need. If I understood your problem correctly, I put in some pseudo code.



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

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

      

+1


source


I would use x as a property, as if it were speed. I'll just ask him to register. In your update () for each frame, you will only need speed in this case, so you just call it. You don't have to constantly check for other values, because they must 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 can add something like this if Unity supports the async keyword. Then you will update your A to look like this:

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


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

      

+1


source


Have you tried this?

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

      

+1


source







All Articles