简体   繁体   English

Unity C#倒计时在场景中持续存在

[英]Unity C# countdown to persist through scenes

Hi I have a C# script written which I can then call inside another script to keep track of the amount of time remaining between different scenes, and then load a scene when the timer reaches 0. I beleive that both scripts are written correctly, but there is no action when the timer reaches 0, I think the issue is that I'm not placing the code in the correct location but I'm not really sure, I've tried adding it to both my start function and my update function. 嗨,我编写了一个C#脚本,然后可以在另一个脚本中调用该脚本以跟踪不同场景之间剩余的时间量,然后在计时器达到0时加载一个场景。我相信这两个脚本都正确编写了,但是在计时器到达0时没有任何反应,我认为问题是我没有将代码放置在正确的位置,但是我不确定,我尝试将其添加到启动函数和更新函数中。

Here is the script for the static class; 这是静态类的脚本;

public static class GlobalCountDown
{
    static DateTime TimeStarted;
    static TimeSpan TotalTime;

    public static void StartCountDown(TimeSpan totalTime)
    {
        TimeStarted = DateTime.UtcNow;
        TotalTime = totalTime;
    }

    public static TimeSpan TimeLeft
    {
        get
        {
            var result = DateTime.UtcNow - TimeStarted;
            if (result.TotalSeconds <= 0)
                SceneManager.LoadScene("Lose");
                return TimeSpan.Zero;           
                //return result;
        }
    }
}

And here is the call I make in each game scene to check the time remaining; 这是我在每个游戏场景中拨打的电话,以检查剩余时间;

GlobalCountDown.StartCountDown (TimeSpan.FromSeconds (5));

I get a warning when compiling the script 'The private field `GlobalCountDown.TotalTime' is assigned but its value is never used' but am not sure how to fix it. 编译脚本“分配了私有字段`GlobalCountDown.TotalTime',但从未使用过它的值”时收到警告,但不确定如何解决。

Any help or advice would be appreciated. 任何帮助或建议,将不胜感激。

Change this 改变这个

var result = DateTime.UtcNow - TimeStarted;

To this 对此

var result = TotalTime - (DateTime.UtcNow - TimeStarted);

In your behaviour do this 按照你的行为

void Start() 
{
  GlobalCountDown.StartCountDown (TimeSpan.FromSeconds (5)); 
}

void Update() 
{
    if (GlobalCountDown.TimeLeft == TimeSpan.Zero)
      SceneManager.LoadScene("Lose");  
}

and remove the SceneManager code from your GlobalCountDown class 并从GlobalCountDown类中删除SceneManager代码

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

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