Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity C# How to check IF (statement) is true for n amount of time?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

float timer:

void Update()
{
  // as long as condition is true, increment timer. 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
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading