0
\$\begingroup\$

I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state-switching) but I can't get the timer to start when I press the boost button.

Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed.

Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas!

Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't.


// Timer
public Text timerText;
private float startTime;
private bool started = false;
private bool finished = false;

  void Start ()
{
    startTime = Time.time;  // get time since scene started
}

void Update ()
{
    if (currentState == State.Alive)
    {
        ProcessBoostInput();
        ProcessRotationInput();
        ProcessFiringInput();
        if (started)
        {
            RunTimer();
        }
    }

}

    private void ProcessBoostInput()
{
    if (Input.GetKey(KeyCode.A) || (CrossPlatformInputManager.GetButton("Fire1")))
    {
        BoostShip();
        PlayBoostSound();

        if (started != true)
        {
            started = true;
        }

    }

    private void RunTimer()
{
    if (finished)
    {

        return;
    }
    else if (started)
    {
        float timeSinceTimerStart = Time.time - startTime;

        string minutes = ((int)timeSinceTimerStart / 60).ToString();
        string seconds = (timeSinceTimerStart % 60).ToString("f3");

        timerText.text = minutes + ":" + seconds;
    }
}
private void StopTimer()
{
    finished = true;
    timerText.color = Color.green;
}
\$\endgroup\$
0
\$\begingroup\$

This line here:

float timeSinceTimerStart = Time.time - startTime;

Measures the time between two timestamps:

  • Time.time (ie. now/this frame)
  • startTime

You're currently setting the startTime timeStamp in the Start() method, which runs just before the object's first updates (ie. generally when the scene is loaded or the object is spawned), so it's recording the time of spawn, not the time you pressed the button.

Instead, you want to set startTime when you press the button to launch the rocket (ie. right where you set started = true). That ensures the earlier timestamp you're measuring from corresponds to the button input, rather than whenever the object happened to get spawned.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you so much! It works perfectly. I spent hours today trying to figure that one out. \$\endgroup\$ – Sam Luxton Jun 7 '18 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.