根据自己的需求写了个简单的计时器,代码如下:
using UnityEngine;
using UnityEngine.UI;
public delegate void CompleteEvent();
public delegate void UpdateEvent(float t);
/// <summary>
///计时器
/// </summary>
public class Timer : MonoBehaviour
{
/// <summary>
/// 是否开始计时
/// </summary>
private bool isStartTime = false;
/// <summary>
/// 总时间
/// </summary>
private int sumTime = 0;
/// <summary>
/// 下一次更改的时间
/// </summary>
private float nextTime = 0;
/// <summary>
/// 显示时间text
/// </summary>
private Text textTime;
public Text TextTime
{
get{return textTime;}
set{textTime = value;}
}
/// <summary>
/// 计时结束
/// </summary>
private CompleteEvent completeEvent;
/// <summary>
/// 实时返回计时
/// </summary>
private UpdateEvent updateEvent;
void Start()
{
}
void Update()
{
if (isStartTime)
{
nextTime += Time.deltaTime;
if (nextTime > 1)
{
if (sumTime <= 0)
{
DestroyTime();
if (completeEvent != null)
completeEvent();
return;
}
sumTime--;
nextTime = 0;
if (updateEvent != null)
updateEvent(sumTime);
if (textTime)
{
textTime.text = string.Format("{0:d2}:{1:d2}", sumTime / 60, sumTime % 60);
if (sumTime <= 10)
{
textTime.color = Color.red;
}
}
}
}
}
/// <summary>
/// 创建计时器
/// </summary>
/// <returns></returns>
public static Timer CreateTimer()
{
GameObject game = new GameObject("Timer");
Timer timer = game.AddComponent<Timer>();
return timer;
}
/// <summary>
/// 开始计时
/// </summary>
/// <param name="time">计时时间</param>
public void StartTimer(int time, CompleteEvent complete, UpdateEvent @event)
{
sumTime = time;
if (textTime)
{
textTime.text = string.Format("{0:d2}:{1:d2}", sumTime / 60, sumTime % 60);
}
completeEvent = complete;
updateEvent = @event;
isStartTime = true;
}
/// <summary>
/// 计时器销毁
/// </summary>
private void DestroyTime()
{
isStartTime = false;
GameObject.Destroy(this.gameObject);
}
}