我编写的这段代码在编辑器上运行良好,但在我的手机上运行不佳。我用的是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 设备,仅当您调用 Application 时
与编辑器不同的是,当用户停止播放模式时会调用此函数。OnApplicationQuit
才会执行.Quit();
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html
关于c# - Android System.DateTime.now 的 Unity 系统时间不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59165345/