抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

ready动画结束后游戏开始,开始计时,直到死亡或者胜利再暂停计时。

新建ClearTime脚本用来更新时间文本,开始动画过后再计时

public class ClearTime : MonoBehaviour
{
[SerializeField] Text timeText;
[SerializeField] VoidEventChannel levelStartedEventChannel;//开始游戏
[SerializeField] VoidEventChannel levelClearedEventChannel;//玩家过关
[SerializeField] StringEventChannel cleardTimeTextEventChannel;//带string参数的频道
[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;
//将clearTime转化为秒,按格式输出
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;//关闭ui显示
}
}

过关时间显示在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;//带string参数的频道
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);
}

评论