简体   繁体   English

在respawn上重启计时器

[英]restart timer on respawn with unity

I'm trying to make a Timer restart when I'm falling down a cliff in Unity. 当我在Unity中摔倒时,我正试图让Timer重启。 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? 你知道如何制作这个吗?

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: 如果您在重新生成的脚本中引用了Timer,那将会很好,例如:

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();
        }

    }
}

Simply call StartTimer() again and reset finished in your method: 只需再次调用StartTimer()并在方法中重置完成:

 // ...
 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: 不要忘记在重新生成的脚本中停止Timer:

public Timer Timer;

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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