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