簡體   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