ready动画结束后游戏开始,开始计时,直到死亡或者胜利再暂停计时。
新建ClearTime脚本用来更新时间文本,开始动画过后再计时
public class ClearTime : MonoBehaviour { [SerializeField] Text timeText; [SerializeField] VoidEventChannel levelStartedEventChannel; [SerializeField] VoidEventChannel levelClearedEventChannel; [SerializeField] StringEventChannel cleardTimeTextEventChannel; [SerializeField] VoidEventChannel playerDefeatedEventChannel; float clearTime; bool stop = true;
private void OnEnable() { levelStartedEventChannel.AddListener(LevelStart); levelClearedEventChannel.AddListener(levelCleared); playerDefeatedEventChannel.AddListener(HideUI); } private void OnDisable() { levelStartedEventChannel.RemoveListener(LevelStart); levelClearedEventChannel.RemoveListener(levelCleared); playerDefeatedEventChannel.RemoveListener(HideUI); } private void FixedUpdate() { if (stop) return; clearTime += Time.fixedDeltaTime; timeText.text = System.TimeSpan.FromSeconds(clearTime).ToString(@"mm\:ss\:ff"); } void LevelStart() { stop = false; } void levelCleared() { HideUI(); cleardTimeTextEventChannel.Broadcast(timeText.text); } void HideUI() { stop = true; GetComponent<Canvas>().enabled = false; } }
|
过关时间显示在Victory Screen
创建带参数的EventChannel.事件频道
创建脚本OneParameterEventChannel设置为泛型,用来继承,方便以后传不同类型参数
public class OneParameterEventChannel<T> : ScriptableObject { event System.Action<T> Delegate; public void Broadcast(T obj) { Delegate?.Invoke(obj); } public void AddListener(System.Action<T> action) { Delegate += action; } public void RemoveListener(System.Action<T> action) { Delegate -= action; } }
|
创建StringEventChannel继承OneParameterEventChannel并且参数类型为<string>
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Data/EventChannels/StringEventChannel", fileName = "StringEventChannel_")] public class StringEventChannel : OneParameterEventChannel<string> { }
|
这样就可以在相应的地方加入参数传递。
在VictoryScreen获胜ui中获取文本对象[SerializeField] Text timeText;
,还有[SerializeField] StringEventChannel clearTimeTextEventChannel;//带string参数的频道
OnEnable()和OnDisable()分别订阅/退订方法SetTimeText(),该方法将获取的string参数赋值给Text timeText
,
[SerializeField] Text timeText; [SerializeField] StringEventChannel clearTimeTextEventChannel; private void OnEnable() { clearTimeTextEventChannel.AddListener(SetTimeText); } private void OnDisable() { clearTimeTextEventChannel.RemoveListener(SetTimeText); } private void SetTimeText(string obj) { timeText.text = obj; }
|
接着看ClearTime脚本,同样序列化cleardTimeTextEventChannel [SerializeField] StringEventChannel cleardTimeTextEventChannel;//带string参数的频道
在过关函数触发时,调用并且将ui上的timeText数据传入StringEventChannel。
void levelCleared() { HideUI(); cleardTimeTextEventChannel.Broadcast(timeText.text); }
|