问题
I made this code that works fine on the editor but not on my phone. I used unity 2017.4.3. The problem is that when the app is closed in the andriod device, it doesnt feel it at all but it works fine in the editor so why doesn't "System.DateTime.now" doesn't work in the andriod device is is there away to make it work?
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 () {
}
}
and the rest in the level manager script
if (PlayerPrefs.HasKey ("lifeTime"))
{
newLifeTime = PlayerPrefs.GetFloat ("lifeTime");
if (CountAllLives)
{
newLifeTime -= TimeMaster.instance.CheckDate ();
}
}
another part of the script
void OnApplicationQuit()
{
PlayerPrefs.SetInt ("PlayerLives",currentLives);
PlayerPrefs.SetFloat ("lifeTime",newLifeTime);
TimeMaster.instance.SaveDate ();
print ("the count down is :" + newLifeTime);
}
回答1:
I have created a dummy scene to implement your functionality and it worked fine for both editor and android device.
One thing you need to make sure is to call Application.Quit();
while quitting, because in case of android devices the OnApplicationQuit
executes only when you call Application.Quit();
unlike the editor were this is called when the user stops playmode.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html
来源:https://stackoverflow.com/questions/59165345/unity-system-time-for-android-system-datetime-now-doesnt-work