简体   繁体   English

Unity c# 在后台设置计时器,即使游戏未激活

[英]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#.请帮助我是统一和 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.也许您应该(在开始游戏时)将加载时间与当前时间进行比较,差异将是经过的时间。

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

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