c# - android System.DateTime.now 的 Unity 系统时间不起作用?
问题描述
我制作的这段代码在编辑器上运行良好,但在我的手机上却不行。我使用了统一 2017.4.3。问题是当应用程序在安卓设备中关闭时,它根本感觉不到,但它在编辑器中工作正常,那么为什么“System.DateTime.now”在安卓设备中不起作用是存在的让它工作?
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
推荐阅读
- deep-linking - xcode 11 beta5 和 swiftui 上的深度链接
- javascript - 使用 Graphql 和 Github API 获取存储库信息
- r - 如何修复 f(...) 中的错误:美学不能随色带而变化
- asp.net-mvc - 如何根据 ASP.NET MVC 中的外键过滤 tolist 查询结果
- spring-boot - 如何在zuul代理spring boot、Sprng security、spring-security-oauth2的下游服务器中获取Security Principal值
- android - 如何在房间使用日期和时间
- android - 在 Flutter 中为选项卡添加底部边框
- java - Android 上的@Module.subcomponents
- angular - 为不同模块中的每个导入添加/加载 SharedModule?
- excel - 带有“#div/0!”的 Excel 公式来计算 Std。偏差