我想制作一個計時器來重置商家的物品價格和數量。如何在遊戲關閉時繼續倒數計時器?
與許多安卓遊戲一樣,有些計時器在不玩遊戲時會繼續下去。 當你不玩遊戲時,計時器應該繼續倒計時。 遊戲關閉時如何保持倒數計時器正在運作?
下面是我倒數計時器
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class margaretSellTimer : MonoBehaviour {
public Text TimerText;
public string dy;
public float days;
public float Hours;
public float Minutes;
public float Seconds;
initMerchantMargaret initMerchants;
player Player;
// Use this for initialization
void Start() {
initMerchants = GameObject.FindGameObjectWithTag ("initMerchant").GetComponent();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent();
StartCoroutine(Wait());
}
// Update is called once per frame
void Update() {
if (days == 1) {
dy = "day ";
} else if (days > 1) {
dy = "days ";
} else {
dy = "day ";
}
if(Seconds < 10)
{
TimerText.text = (days + " " + dy + Hours + ":" + Minutes + ":0" + Seconds);
}
if(Seconds > 9)
{
TimerText.text = (days + " " + dy + Hours + ":" + Minutes + ":" + Seconds);
}
}
public void CountDown()
{
if(Seconds <= 0) {
if(Minutes > 0) {
MinusMinute();
Seconds = 60;
}
}
if (Minutes <= 0) {
if(Hours > 0) {
MinusHours();
Minutes = 59;
Seconds = 60;
}
}
if (Hours <= 0) {
if(days > 0) {
MinusDays();
Hours = 23;
Minutes = 59;
Seconds = 60;
}
}
if(Minutes >= 0)
{
MinusSeconds();
}
if(Hours <= 0 && Minutes <= 0 && Seconds <= 0 && days <= 0)
{
StopTimer();
}
else
{
Start();
}
}
public void MinusDays() {
days -= 1;
}
public void MinusHours() {
Hours -= 1;
}
public void MinusMinute() {
Minutes -= 1;
}
public void MinusSeconds() {
Seconds -= 1;
}
public IEnumerator Wait() {
yield return new WaitForSeconds(1);
CountDown();
}
public void StopTimer() {
Seconds = 5;
Minutes = 0;
Hours = 0;
days = 0;
Player.margaretItemSell.Clear();
Player.productMargaretSell.Clear();
Player.productSellMargaret.Clear();
initMerchants.margaretSell();
Start();
}
}
感謝。
+2
而不是繼續的計時器,儲存狀态,當你退出遊戲。然後,當遊戲再次開始時,計算儲存狀态和目前時間之間的偏移量,并從那裡繼續計時。 –
+1
^那麼這是一個很好的解決方案。但我猜如果目的是在一定時間後發送推送通知,那麼可能需要使用原生android代碼或某些第三方插件來建立背景服務。 –
+0
為了上帝的緣故,隻需使用Invoke。 –