遊戲簡單控制邏輯Clock類,邏輯clock類
出處:http://blog.csdn.net/u010019717
author:孫廣東 時間:2015.3.24 23:00
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}}
還不錯吧!