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;
    }
}

 输出如下

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值