简体   繁体   中英

Unity c# set timer on background even if game is not active

I have a game where I have time to give energy. My timer works fine when game is active but when game is inactive the time pauses and after I start game again the timer starts from wher it was left. I want keep timer going even if the game is inactive and add energy.

using System;
using UnityEngine;
using UnityEngine.UI;

public class EnergyAdder : MonoBehaviour
{
    // Start is called before the first frame update
    public float waitTime = 600;
    Timer timer;
    public GameRoot gameRoot;
    void Awake()
    {
        //timer = new Timer(waitTime);
        float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
        timer = new Timer(remainingTime);
    }


    // Update is called once per frame
    void Update()
    {
        if (gameRoot.energyCap >= 5)
        {
            GetComponent<Text>().text = "Full";
            timer.refresh();
        }
        else
        {
            timer.countDown();
            if (timer.isFinished())
            {
                timer = new Timer(waitTime);
                timer.refresh();
                gameRoot.AddEnergy(1);
            }
            UpdateClock();
        }
    }
    void UpdateClock()
    {
        int seconds = ((int)timer.timeLeft) % 60;
        int minutes = (int)(timer.timeLeft / 60);
        GetComponent<Text>().text =  minutes.ToString() + ":" + seconds.ToString("00");

    }

    void OnApplicationQuit()
    {
            PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
    }
}

Please help I'm new to unity and c#.

What you are doing is saving time value when you left, and load that value when you start the game again.

Maybe you should (when start the game) compare that loaded time with the current time, the difference will be the time elapsed.

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