简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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