unity七日签到系统

一个用于七日签到的系统,仅供参考,时间以凌晨12点为每日分割。
效果如下:
unity七日签到系统_第1张图片
代码

using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

/// 
/// 7日签到系统
/// *无需服务器,客户端自给自足获取网络时间
/// *author:passion
/// 
public class SignView : MonoBehaviour {

    public const string SignNumPrefs = "SignNum";
    public const string SignDataPrefs = "SignData";
    public Toggle[] toggles;

    string ntpUrl = "http://cgi.im.qq.com/cgi-bin/cgi_svrtime";

    int signNum;//签到次数
    DateTime today;//今日日期
    //DateTime today = new DateTime(2018, 10, 1);
    DateTime signData;//上次签到日期


    //自定义日期,测试时使用
    //private void Awake()
    //{
    //    DateTime yestody = new DateTime(2018, 9, 20);
    //    PlayerPrefs.SetString(SignDataPrefs, yestody.ToString());
    //    PlayerPrefs.SetInt(SignNumPrefs, 1);
    //}

    //使用协程,获取ntp时间
    IEnumerator Start () {
        WWW www = new WWW(ntpUrl);
        yield return www;
        today = DateTime.Parse(www.text);

        //新的签到周期,需要清除签到存档
        if (NeedClean())
        {
            PlayerPrefs.DeleteKey(SignNumPrefs);
            PlayerPrefs.DeleteKey(SignDataPrefs);
        }

        signNum = PlayerPrefs.GetInt(SignNumPrefs, 0);
        signData = DateTime.Parse(PlayerPrefs.GetString(SignDataPrefs, DateTime.MinValue.ToString()));

        RefreshView();
    }
	
    //签到按钮点击
	public void OnSignClick()
    {
        if(!IsOneDay(signData, today))
        {
            signNum++;
            signData = today;

            //更新存档
            PlayerPrefs.SetString(SignDataPrefs, today.ToString());
            PlayerPrefs.SetInt(SignNumPrefs, signNum);
            //刷新视图
            RefreshView();
            //给用户加金币
            UserGift();
        }
    }

    //刷新视图
    void RefreshView()
    {
        for (int i = 0; i < signNum; i++)
        {
            toggles[i].isOn = true;
        }
    }

    //判断是否是同一天
    bool IsOneDay(DateTime t1,DateTime t2)
    {
        return (t1.Year == t2.Year &&
         t1.Month == t2.Month &&
          t1.Day == t2.Day);
    }

    //获取任意日期的周一时间
    DateTime GetMonday(DateTime t)
    {
        //上次签到日期小于本周一
        int offset = (int)t.DayOfWeek;
        offset = offset == 0 ? 7 : offset;
        return t.AddDays(1 - offset);
    }

    //需要清除
    bool NeedClean()
    {
        DateTime curMonday = GetMonday(today);
        DateTime signMonday = GetMonday(signData);

        return (IsOneDay(curMonday,signMonday));
    }

    //给用户加金币
    void UserGift()
    {

    }
}

你可能感兴趣的:(Unity)