我有一個代碼,如果玩家的分數超過 7000 分,則每 24 小時一次(86400000 milliseconds)
,然后他將所有高于 7000 的分數除以 2,即使關閉應用程式,我如何才能使此條件每 24 小時滿足一次?
using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using Random=UnityEngine.Random;
public class LeagueClock : MonoBehaviour
{
private ulong TimeToReset;
public float msToWait = 86400000f;
private int scrMain;
private bool Flag;
private void Start(){
scrMain = PlayerPrefs.GetInt("scrMain");
TimeToReset = ulong.Parse(PlayerPrefs.GetString("LastReset"));
Debug.Log(DateTime.Now);
}
private void Update(){
if (scrMain > 7001){
if (IsResetTrue()){
scrMain -= (scrMain-7000)/2;
PlayerPrefs.SetInt("scrMain", scrMain);
TimeToReset = (ulong)DateTime.Now.Ticks;
PlayerPrefs.SetString("LastReset", TimeToReset.ToString());
}
Flag = true;
}
}
private bool IsResetTrue(){
ulong diff = ((ulong)DateTime.Now.Ticks - TimeToReset);
ulong m = diff / TimeSpan.TicksPerMillisecond;
float secondsLeft = (float)(msToWait - m) / 1000.0f;
Debug.Log(secondsLeft " / " scrMain);
if (secondsLeft < 0){
return true;
}
return false;
}
}
uj5u.com熱心網友回復:
您需要更改代碼以識別時間間隔何時經過多次。
using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using Random=UnityEngine.Random;
public class LeagueClock : MonoBehaviour
{
private ulong TimeLastReset;
[SerializeField] private float msToWait = 86400000f;
[SerializeField] private int scoreThreshold = 7000;
private int scrMain;
private void Start(){
scrMain = PlayerPrefs.GetInt("scrMain");
TimeLastReset = ulong.Parse(PlayerPrefs.GetString("LastReset", "0"));
Debug.Log(DateTime.Now);
}
private void Update(){
if (scrMain > scoreThreshold) {
//apply the action for each interval that has passed.
//For example, if the interval is 24 hours, and 49 hours
//have passed, that's 2 intervals, so we reduce the score
//twice.
int intervalsPassed = GetIntervalsPassed();
if (intervalsPassed > 0){
for (int i = 0; i < intervalsPassed; i ) {
ReduceScore();
}
PlayerPrefs.SetInt("scrMain", scrMain);
TimeLastReset = (ulong)DateTime.Now.Ticks;
PlayerPrefs.SetString("LastReset", TimeLastReset.ToString());
}
}
}
private void ReduceScore() {
scrMain -= (scrMain-scoreThreshold)/2;
}
//returns the number of full time intervals that have passed since
//we last reduced the score
private int GetIntervalsPassed(){
ulong diff = ((ulong)DateTime.Now.Ticks - TimeLastReset);
ulong ms = diff / TimeSpan.TicksPerMillisecond;
float secondsLeft = (float)(msToWait - ms) / 1000.0f;
int intervalsPassed = Mathf.FloorToInt(ms / msToWait);
Debug.Log($"SecondsLeft: {secondsLeft} | Intervals: {intervalsPassed} | Score: {scrMain}");
return intervalsPassed;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485848.html
下一篇:站在移動平臺上無法移動