适用于android System.DateTime.now的Unity System Time不起作用?



我编写了这段代码,在编辑器上工作正常,但在手机上不能。我使用了 unity 2017.4.3。 问题是,当应用程序在 andriod 设备中关闭时,它根本感觉不到,但它在编辑器中工作正常,那么为什么"System.DateTime.now"在 andriod 设备中不起作用是有没有让它工作?

using UnityEngine;
using System.Collections;
using System;
public class TimeMaster : MonoBehaviour {
DateTime currentDate;
DateTime oldDate;
public string saveLocation;
public static TimeMaster instance;
// Use this for initialization
void Awake () {
instance = this;
saveLocation = "LastSavedDate1";
}
public float CheckDate()
{
currentDate = System.DateTime.Now;
string tempString = PlayerPrefs.GetString (saveLocation, "1");
long tempLong = Convert.ToInt64 (tempString);
DateTime oldDate = DateTime.FromBinary (tempLong);
print ("oldDate : " + oldDate);
TimeSpan difference = currentDate.Subtract (oldDate);
print ("difference :" + difference);
return(float)difference.TotalSeconds;
}
public void SaveDate ()
{
PlayerPrefs.SetString (saveLocation, System.DateTime.Now.ToBinary ().ToString ());
print ("saving this date to player prefs" + System.DateTime.Now);
}
// Update is called once per frame
void Update () {
}
}

其余部分在关卡管理器脚本中

if (PlayerPrefs.HasKey ("lifeTime"))
{    
newLifeTime = PlayerPrefs.GetFloat ("lifeTime");
if (CountAllLives) 
{
newLifeTime -= TimeMaster.instance.CheckDate ();
}
} 

脚本的另一部分

void OnApplicationQuit()
{
PlayerPrefs.SetInt ("PlayerLives",currentLives);
PlayerPrefs.SetFloat ("lifeTime",newLifeTime);
TimeMaster.instance.SaveDate ();
print ("the count down is :" + newLifeTime);           
}

我创建了一个虚拟场景来实现您的功能,它适用于编辑器和 android 设备。 您需要确保的一件事是在退出时调用Application.Quit();,因为在 android 设备的情况下,OnApplicationQuit仅在您调用Application.Quit();时执行,这与编辑器不同,这是在用户停止播放模式时调用的。

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html

最新更新