u3d c# 写一个通用倒计时器
2015-07-30 10:33
405 查看
计时器管理类
using UnityEngine; using System.Collections; using System; public class TimerManager : MonoBehaviour { private static TimerManager m_instance = null; public static TimerManager Instance { get { return m_instance; } } void Awake() { m_instance = this; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void GetTimer(int second,MyTimer.Mode mode,MyTimer.TimesUp TimesUpDelegate,MyTimer.PerSecond PerSecondDelegate=null) { GameObject Timer = Instantiate(Resources.Load("Prefabs/Time/MyTimer")) as GameObject; Timer.transform.parent = transform; Timer.GetComponent<MyTimer>().SetTimer(second); Timer.GetComponent<MyTimer>().SetMode(mode); Timer.GetComponent<MyTimer>().SetTimesUpDelegate(TimesUpDelegate); Timer.GetComponent<MyTimer>().SetPerSecondDelegate(PerSecondDelegate); Timer.GetComponent<MyTimer>().StartTimer(); } public String GetTimeBySecond(float seconds) { return DateTime.Parse(DateTime.Now.ToString("00:00:00")).AddSeconds(seconds).ToString("HH:mm:ss"); } }倒计时类
using UnityEngine;using System.Collections;public class MyTimer : MonoBehaviour { public enum Mode { PerSecond, Once, Loop } public float TotalSeconds; public Mode m_mode; public delegate void TimesUp(); public TimesUp timesUp = null; public delegate void PerSecond(float timesLeft); public PerSecond perSecond = null; int m_leaveSeconds; void Awake() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void StartTimer() { switch (m_mode) { case Mode.PerSecond: StartCoroutine(TimerBeginPerSocond()); break; case Mode.Once: StartCoroutine(TimerBegin()); break; case Mode.Loop: break; } } public void SetTimer(int seconds) { TotalSeconds = seconds; } public void SetMode(Mode mode) { m_mode = mode; } public void SetTimesUpDelegate(TimesUp del) { timesUp = del; } public void SetPerSecondDelegate(PerSecond del) { perSecond = del; } IEnumerator TimerBegin() { yield return new WaitForSeconds(TotalSeconds); timesUp(); Destroy(gameObject); } IEnumerator TimerBeginPerSocond() { yield return new WaitForSeconds(1f); if ((TotalSeconds--) > 0) { perSecond(TotalSeconds); StartCoroutine(TimerBeginPerSocond()); } else { timesUp(); Destroy(gameObject); } } }分别挂在两个预制上。管理类预先加载到场景中
public void CreateTimerManager() { GameObject TimerManager = GameObject.Instantiate(Resources.Load("Prefabs/Manager/TimerManager")) as GameObject; TimerManager.name = "TimerManager"; }每请求一个定时器,调管理类函数,选择模式和返回的回调。可选每秒返回,每次返回,循环也可以但是暂时没这个需求
相关文章推荐
- c# 双缓冲 技术与例子(解决应用程序闪烁问题)
- C# GDI+双缓冲技术
- 浅谈C#中的双缓冲
- C#实现12306自动登录的方法
- C# Debug与release之间的一些小差异
- C#中IList<T>与List<T>的区别感想
- C#中override和overload的区别
- C# WinForm程序退出的方法
- C#与.NET概述
- C#生成DBF文件
- c#调用存储过程
- c#根据公式进行自动计算的实现
- C#关于使用正则表达式解析字符串
- C#中的WebBrowser控件的使用
- 用C#写一个多进程监控自动关机工具
- C#+AE 判断点是否在面内的方法
- C#:将子Form加入父Form中
- C#使用sort方法对数组进行快速排序
- C# RichTextBox 中用栈实现代码的自动缩进
- C#的注释和快速开启工具的命令