unity3D UI界面计时器

 计时器不难写,但是麻烦。运行界面自然不用说,后台也要计时的话就需要用到保存了,接下来就直接上代码了,里面有些无用的东西还请无视!^_^

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

/// <summary>
/// 利用系统时间和本地存储做倒计时并显示
/// </summary>

public class CountDownTime : MonoBehaviour
{
    [Header("免费金币/倒计时")]
    public GameObject freeGold;
    [Header("倒计时")]
    public Text countDownText;
    public Sprite freeGold_1;
    public Sprite freeGold_2;
    private int countDownT;

    private static readonly string Key_Stretch_CountDownTime = "Key_Stretch_CountDownTime";
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
       CountDownTime();
        //重置
       if (Input.GetMouseButtonDown(0)) {
           PlayerPrefs.SetString(Key_Stretch_CountDownTime, DateTime.Now.ToString());
       }
    }

    //倒计时
    public void CountDownTime()
    {
        //TimeSpan时间差
        TimeSpan ts = DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString(Key_Stretch_CountDownTime));
        //TimeSpan.TotalSeconds时间差的总秒数,,倒计时长以300秒为例
        if (ts.TotalSeconds < 300f)
        {
            countDownT = (int)(300 - ts.TotalSeconds);
            countDownText.text = string.Format("{0:D2}:{1:D2}", (int)countDownT / 60, countDownT % 60);
            //freeGold.sprite = Resources.Load("Image/pic", typeof(Sprite)) as Sprite;
            freeGold.GetComponent<Image>().sprite = freeGold_2;
            countDownText.gameObject.SetActive(true);
            freeGold.gameObject.GetComponent<Button>().enabled = false;
        }
        else
        {
            freeGold.GetComponent<Image>().sprite = freeGold_1;
            countDownText.gameObject.SetActive(false);
            freeGold.gameObject.GetComponent<Button>().enabled = true;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值