Home > Back-end >  Unity C# How to check IF (statement) is true for n amount of time?
Unity C# How to check IF (statement) is true for n amount of time?

Time:07-16

I have an If statement that returns true or false, naturally. How do I check the condition for n amount of time (frames, seconds)? I need the bool to return false only if condition is true for half a second.

CodePudding user response:

Put some code in your Update method and use a float member variable and add Time.deltaTime. The update method triggers every frame. Once the variable is over 0.5f do your magic.

public class MyScript : MonoBehaviour
{
    float timer:

    void Update()
    {
        // If condition is false, reset timer and return out. Replace condition with your logic.
        if (!condition)
        {
            timer = 0.0f;
            return;
        }
      
        timer  = Time.deltaTime:
        if (timer > 0.5f)
        {
            // do stuff

            timer = timer - 0.5f; // reset timer
        }
    }
}
  • Related