Lucas Doppelt
Lucas Doppelt

Reputation: 85

restart timer on respawn with unity

I'm trying to make a Timer restart when I'm falling down a cliff in Unity. I already have a script that makes me respawn on threshold after a certain height. I would like to make the same thing but instead of being respawned, the timer restarts.

public class Timer : MonoBehaviour {

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

     void Update () 
     {      
         if(!started || finished)
             return;

         float t = Time.time - startTime;

         string minutes = ((int) t/60).ToString();
         string seconds = (t%60).ToString("f2");

         timerText.text = minutes + ":" + seconds;      
     }

     public void StartTimer ()
     {
         started = true;
         startTime = Time.time;
     }

     public void StopTimer()
     {
         finished = true;
         timerText.color = Color.yellow;      
     }   
 }

My respawning script is on my camera rig and it's

public class respawn : MonoBehaviour
{
    public float threshold;

    void FixedUpdate()
    {
        if (transform.position.y < threshold)
            transform.position = new Vector3(403, 266, 337);

    }
}

Do you have any idea how to make this?

Upvotes: 3

Views: 1017

Answers (2)

Antonio Garcia
Antonio Garcia

Reputation: 147

You just need to restart the timer when you meet the falling condition. Would be nice if you have a reference to the Timer in your respawn script, something like:

public class respawn : MonoBehaviour
{
    public Timer timer;
    public float threshold;

    void FixedUpdate()
    {
        if (transform.position.y < threshold)
        {
        //transform.position = new Vector3(403, 266, 337);
        timer.StartTimer();
        }

    }
}

Upvotes: 4

Ludovic Feltz
Ludovic Feltz

Reputation: 11916

Simply call StartTimer() again and reset finished in your method:

 // ...
 public void StartTimer ()
 {
     finished = false;
     started = true;
     startTime = Time.time;
 }

 public void StopTimer()
 {
     finished = true;
     timerText.color = Color.yellow;      
 } 

Do not forget to stop your Timer in your respawn script:

public Timer Timer;

void FixedUpdate()
{
    if (transform.position.y < threshold)
    {
        Timer.StopTimer();
        transform.position = new Vector3(403, 266, 337);
    }

}

Upvotes: 3

Related Questions