c# - Android System.DateTime.now 的 Unity 系统时间不起作用?

标签 c# unity-game-engine 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 设备,仅当您调用 Application 时 OnApplicationQuit 才会执行.Quit(); 与编辑器不同的是,当用户停止播放模式时会调用此函数。

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

关于c# - Android System.DateTime.now 的 Unity 系统时间不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59165345/

相关文章:

java - 在 Parse 后端查找当前时间和上次更新时间之间的差异

php - Timespan - 检查 mysql 中的工作日和一天中的时间

与 u-blox gps 的 C# 串行通信

unity-game-engine - 获取android unity3d中的drawcalls数量

unity-game-engine - OnTriggerEnter 被调用但变量从未设置

unity-game-engine - 如何扩展Unity应用程序?

计算所有函数的执行时间

c# - 创建没有自动生成代理的 WCF 客户端

c# - 更新MongoDB文档后如何获取_id?

java - IEEE 754 和语言之间的值范围