Unity制作app离线计时器

先讲个大概思路

1.退出应用后,本地保存上次退出时间(安卓读取数据)

2.进入应用时,用现在的时间减去上次退出的时间,获得离线时间

本地数据

using System;
using System.Collections.Generic;

[Serializable]
public class GameDate
{
    //这个类是获取数据和传递数据的
 
    private DateTime time;

    /// <summary>
    /// 记录离线的时间
    /// </summary>
    public void SetOutLineTime(DateTime dateTime)
    {
        time = dateTime;
    }
 

 
    public DateTime GetOutLineTime()
    {
        return time;
    }



}

记录离线时间 

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;

public class GameInfomation : MonoBehaviour
{

    //时间
    private DateTime OutLineTime;

    public void Save()
    {
        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = File.Create(Application.persistentDataPath + "/GameData.data"))
            {
                //保存数据
                date.SetOutLineTime(OutLineTime);
                bf.Serialize(fs, date);
            }
        }
        catch (System.Exception e)
        {

            Debug.Log("失败创建" + e.Message);
        }
    }

    private void Read()
    {
        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = File.Open(Application.persistentDataPath + "/GameData.data", FileMode.Open))
            {
                date = (GameDate)bf.Deserialize(fs);

            }
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
 private void OnApplicationPause(bool isFocs)
    {
       if(isFocs)
       {
         OutLineTime = DateTime.Now;
         Debug.Log("退出时间=" + OutLineTime);
         Save();
       }
    }
}

获取当前时间减去离线时间

public class OutLineSync : MonoBehaviour
{
    private float AllOutTime;
    private float OutLineTotal
    // Start is called before the first frame update
    void Start()
    {
        OutLineTotal = DateTime.Now - GameInfomation._Instance.GetOutTime();
        AllOutTime = GetFloatOuttime(OutLineTotal);
        Debug.Log("上次离线时间=" + GameInfomation._Instance.GetOutTime());  
        Debug.Log("现在时间=" + DateTime.Now);
    }

  public  float GetFloatOuttime(TimeSpan Ts)
    {
        if (Ts.Days >= 1)
        {
            FloatOutTime = 24 * 3600;
        }
        else if (Ts.Days < 1)
        {
            Debug.Log("时间差值=" + Ts);
            FloatOutTime = Ts.Hours *3600 + Ts.Minutes * 60 + Ts.Seconds;
        }
        return FloatOutTime;
    }
}

 输出如下

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页