首页 > 解决方案 > 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);           
}

标签: c#unity3dtime

解决方案


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

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


推荐阅读