在Unity中,我试图计算应用程序关闭后的秒数,以找出玩家赚了多少硬币。我测试了我的代码,但我的公式似乎,因为它给我不同的值比我预期的。
public class CoinGenerator : MonoBehaviour
{
[SerializeField] private Upgradable building;
[SerializeField] private int coinsPerHourBase = 200; // Default coins per hour
[SerializeField] private int capacityBase = 1000; // Default capacity
private int buildingLevel, coinsPerHour, capacity;
private float coinsAccumulated;
public int BuildingLevel { get { return buildingLevel; } }
public float CoinsAccumulated { get { return coinsAccumulated; } }
private void Start()
{
SetBuildingLevel();
SetCoinsPerHourAndCapacity(buildingLevel);
coinsAccumulated += CoinsEarnedSincePlayerQuit();
}
private void Update()
{
// Calculate and accumulate coins over time
float generatedCoins = (coinsPerHour * (Time.deltaTime / 3600f));
coinsAccumulated = Mathf.Clamp(coinsAccumulated + generatedCoins, 0, capacity);
//Debug.Log(coinsAccumulated);
}
public void SetCoinsPerHourAndCapacity(int buildingLevel)
{
this.buildingLevel = buildingLevel;
coinsPerHour = coinsPerHourBase * buildingLevel; // Scale based on building level
capacity = capacityBase * buildingLevel; // Scale capacity based on building level
}
// Gets current ugrade level in Upgradable Component
public void SetBuildingLevel()
{
buildingLevel = building.CurrentUpgradeLevel;
SetCoinsPerHourAndCapacity(buildingLevel);
}
// Returns coins earned since player quit the scene
private float CoinsEarnedSincePlayerQuit ()
{
// Subtract time now to time that the app last quit
System.TimeSpan secondsSinceQuit = System.DateTime.Now.Subtract(TimeQuitRecorder.instance.TimeQuit);
// Calculate coins earned since last quit
float generatedCoins = coinsPerHour * ((float)secondsSinceQuit.TotalSeconds / 3600f);
//
// Clamp value to building capacity
float coinsEarned = Mathf.Clamp(generatedCoins, 0, capacity);
Debug.Log("Seconds: " + secondsSinceQuit.TotalSeconds);
return coinsEarned;
}
字符串
CoinsEarnedSincePlayerQuit()方法负责计算从退出应用程序到加载应用程序的时间。它从TimeQuitRecorder Singleton获取退出时间,并从CoinGenerator加载时获取加载时间。
using UnityEngine;
public class TimeQuitRecorder : MonoBehaviour
{
public static TimeQuitRecorder instance;
private static System.DateTime _timeQuit;
PlayerData playerData;
public System.DateTime TimeQuit{ get { return _timeQuit; } }
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
return;
}
}
private void OnApplicationQuit()
{
_timeQuit = System.DateTime.Now;
}
}
型
TimeQuitRecorder将应用程序关闭时的时间保存到私有变量_timeQuit中,然后可以通过TimeQuit访问该变量。
我停止了大约2分钟的场景,然后当我加载回来,它显示63826919893. 997,而不是大约120的值。
1条答案
按热度按时间xxhby3vn1#
您可以尝试为游戏构建一个保存系统,但检查上次关闭游戏后经过了多少秒的最简单方法是使用PlayerPrefs和TimeSpan(不要使用Unity Time)以及任何秒来保存当前时间。
祝你好运。