繁体   English   中英

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

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

我有一个游戏,我有时间给予能量。 当游戏处于活动状态时,我的计时器工作正常,但当游戏处于非活动状态时,时间会暂停,并且在我再次开始游戏后,计时器会从它离开的地方开始。 即使游戏处于非活动状态,我也希望保持计时器继续运行并增加能量。

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

请帮助我是统一和 c# 的新手。

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

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

暂无
暂无

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

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