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

Unity c#即使游戏未激活,也在后台设置计时器,c#,unity3d,C#,Unity3d,我有一场比赛,在那里我有时间给予能量。当游戏处于活动状态时,我的计时器工作正常,但当游戏处于非活动状态时,计时器会暂停,并且在我再次启动游戏后,计时器会从离开时开始计时。 我想让计时器继续运行,即使游戏处于非活动状态,并增加能量 using System; using UnityEngine; using UnityEngine.UI; public class EnergyAdder : MonoBehaviour { // Start is called before the fi

我有一场比赛,在那里我有时间给予能量。当游戏处于活动状态时,我的计时器工作正常,但当游戏处于非活动状态时,计时器会暂停,并且在我再次启动游戏后,计时器会从离开时开始计时。 我想让计时器继续运行,即使游戏处于非活动状态,并增加能量

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

使用系统;
使用UnityEngine;
使用UnityEngine.UI;
公共类能源供应商:单一行为
{
//在第一帧更新之前调用Start
公共浮动等待时间=600;
定时器;
公共GameRoot GameRoot;
无效唤醒()
{
//定时器=新定时器(等待时间);
float remainingTime=PlayerPrefs.GetFloat(“TimeOnExit”);
定时器=新定时器(剩余时间);
}
//每帧调用一次更新
无效更新()
{
如果(gameRoot.energyCap>=5)
{
GetComponent().text=“Full”;
timer.refresh();
}
其他的
{
计时器。倒计时();
if(timer.isFinished())
{
定时器=新定时器(等待时间);
timer.refresh();
gameRoot.附加能(1);
}
updatelock();
}
}
void updatelock()
{
int秒=((int)timer.timeLeft)%60;
int分钟=(int)(timer.timeLeft/60);
GetComponent().text=minutes.ToString()+“:”+seconds.ToString(“00”);
}
在Application Quit()上无效
{
PlayerPrefs.SetFloat(“TimeOnExit”,timer.timeLeft);
}
}

请帮助我,我是unity和c#的新手。

您所做的是在离开时保存时间值,并在重新开始游戏时加载该值

也许你应该(在开始游戏时)将加载的时间与当前时间进行比较,差异将是经过的时间