简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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