游戏简单控制逻辑Clock类

unity中有协程可以提供延迟的功能等。 但是很多时候我们并不想使用,,那就自己在Update中控制时间呗。

于是我封装了这个类。

若要使用这个时钟,首先将其实例化,调用Reset函数设置正确的时间值,调用Update每一帧更新。任何想要被事件通知的类需要实现 IClockListener 接口,和使用AddListener方法订阅事件。可以用RemoveListener移除侦听器(很强大吧!)时钟能够使用Pause方法独立于 Time.timeScale 被暂停 (和使用 Unpause恢复继续)

using System.Collections.Generic;namespace Gamelogic{public class Clock{private float time;private int timeInSeconds;private readonly List<IClockListener> listeners;// 监听列表#regionpublic bool IsPaused{get; private set;}public bool IsDone{get; private set;}public float Time{get{return time;}}public int TimeInSeconds{get{return timeInSeconds;}}#endregion// 构造函数public Clock(){listeners = new List<IClockListener>();IsPaused = true;Reset(0);}public void AddClockListener(IClockListener listener){listeners.Add(listener);}public void RemoveClockListener(IClockListener listener){listeners.Remove(listener);}public void Reset(float startTime){time = startTime;IsDone = false;CheckIfTimeInSecondsChanged();}public void Unpause(){IsPaused = false;}public void Pause(){IsPaused = true;}// 时间每帧更新public void Update(){if (IsPaused) return;if (IsDone) return;time -= UnityEngine.Time.deltaTime;CheckIfTimeInSecondsChanged();if (time <= 0){time = 0;IsDone = true;for (int i = 0;i< listeners.Count;i++){listeners[i].OnTimeOut();}}}// 判断是否发生秒的改变private void CheckIfTimeInSecondsChanged(){var newTimeInSeonds = (int)time;if (newTimeInSeonds == timeInSeconds) return;timeInSeconds = newTimeInSeonds;for (int i = 0;i< listeners.Count;i++){listeners[i].OnSecondsChanged(timeInSeconds);}}}// 时钟监听者类型接口public interface IClockListener{void OnSecondsChanged(int seconds);void OnTimeOut();}}

然后我简单测试了一下,在unity4.6中。 如下倒计时:

using UnityEngine.UI;namespace Gamelogic.Examples{public class ClockTest : IClockListener{public Text clockText;public Text messageText;private Clock clock;// 时钟对象public void Start(){clock = new Clock();clock.AddClockListener(this);// 对时钟监听Reset();}public void Update(){clock.Update();}public void Pause(){clock.Pause();}public void Unpause(){clock.Unpause();}public void Reset(){clock.Reset(5);clock.Unpause();}#region IClockListener methods// 实现接口方法public void OnSecondsChanged(int seconds){clockText.text = clock.TimeInSeconds.ToString();}public void OnTimeOut(){messageText.gameObject.SetActive(true);}#endregion}}

还不错吧!

片的时光如浮云般流过,我们的青春单薄的穿梭在蓝天之上。

游戏简单控制逻辑Clock类

相关文章:

你感兴趣的文章:

标签云: