Duddle Diddle
Duddle Diddle

Reputation: 109

How to make a countdown in Unity

I'm currently working on a countdown or count up in my case, but I'm having trouble doing certain actions on the right time, mostly because my script is flawed. My script is not right on point, I made it so when it's between to floats and action will happen, and that fluctuates between some timing with an action and a sound.

public float timeValue;

private void FixedUpdate()
{
    timeValue += Time.deltaTime;

    if(timeValue > 25.2 && timeValue < 25.4)
    {
        //Random Animation
    }
    if(timeValue > 26.2 && timeValue < 26.4)
    {
        //Sound Effect connected to Random Animation
    }
}

As you can see, it varies from time to time when timeValue hits between those floats, because it doesn't hit the same float everytime. I want a solution to do it right on point.

Upvotes: 0

Views: 868

Answers (2)

MohammadReza Arashiyan
MohammadReza Arashiyan

Reputation: 343

In addition to Vansmos answer, You can use other time's method like DateTime.
DateTime has different functions to give you current time in miliseconds, seconds, hours or etc. for example:

var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

Different methods are mentioned here: Link

Upvotes: 0

vasmos
vasmos

Reputation: 2586

You are using FixedUpdate() which is for the physics loop , you want Update(), the FixedUpdate() loop is timed to run at a specific frequency and is likely messing up deltaTime. You can also just use Time.time to get the total amount of time since the application started.

private void Update()
{
    timeValue += Time.deltaTime;

    if(timeValue > 25.2 && timeValue < 25.4)
    {
        //Random Animation
    }
    if(timeValue > 26.2 && timeValue < 26.4)
    {
        //Sound Effect connected to Random Animation
    }
}

You can also simplify your code by using Time.time to get the total time since the start of the application.

private void Update()
{

    if(Time.time > 25.2 && Time.time < 25.4)
    {
        //Random Animation
    }
    if(Time.time > 26.2 && Time.time < 26.4)
    {
        //Sound Effect connected to Random Animation
    }
}

Upvotes: 1

Related Questions