一个非常简单的事件监听与广播系统,功能也比较简单,但是还是挺实用的,可以用来解耦
实现功能:
- 添加事件监听
- 移除事件监听
- 广播消息
消息类型枚举:
/// <summary>
/// 事件类型枚举
/// </summary>
public enum EventType
{
ShowText,
HideText
}
消息中心:
using System;
using System.Collections.Generic;
/// <summary>
/// 事件中心
/// </summary>
public class EventCenter
{
private static Dictionary<EventType, Action<object>> m_EventDict = new Dictionary<EventType, Action<object>>();
/// <summary>
/// 添加事件监听
/// </summary>
public static void AddListener(EventType eventType, Action<object> callback)
{
if (!m_EventDict.ContainsKey(eventType))
{
m_EventDict.Add(eventType, null);
}
m_EventDict[eventType] += callback;
}
/// <summary>
/// 移除事件监听
/// </summary>
public static void RemoveListener(EventType eventType, Action<object> callback)
{
if (!m_EventDict.ContainsKey(eventType))
return;
if (m_EventDict[eventType] == null)
return;
m_EventDict[eventType] -= callback;
}
/// <summary>
/// 广播
/// </summary>
public static void Broadcast(EventType eventType,object data)
{
if (!m_EventDict.ContainsKey(eventType))
return;
Action<object> callback = m_EventDict[eventType];
if (callback != null)
{
callback(data);
}
}
}
效果演示:
1.再Canvas下创建一个Text文本,两个按钮ShowBtn和HideBtn,将TextUI挂载到Text上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextUI : MonoBehaviour
{
private Text m_Text;
private void Start()
{
m_Text = GetComponent<Text>();
// 为显示和隐藏添加监听
EventCenter.AddListener(EventType.ShowText, Show);
EventCenter.AddListener(EventType.HideText, Hide);
this.gameObject.SetActive(false);
}
private void Show(object data)
{
string str = data as string;
m_Text.text = str;
this.gameObject.SetActive(true);
}
private void Hide(object data)
{
this.gameObject.SetActive(false);
}
private void OnDestroy()
{
// 再物体销毁的时候移除监听
EventCenter.RemoveListener(EventType.ShowText, Show);
EventCenter.RemoveListener(EventType.HideText, Hide);
}
}
2.再Canvas上挂载Test脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public void OnShowBtnClicked()
{
EventCenter.Broadcast(EventType.ShowText, "你好,我是Blinkedu");
}
public void OnHideBtnClicked()
{
EventCenter.Broadcast(EventType.ShowText,null);
}
}
3.为ShowBtn和HideBtn添加点击事件,指定方法为OnShowBtnClicked()和OnHideBtnClicked()
当然,这个还非常的不完善,比如添加监听的方法必须要有一个object类型的参数,用来传递数据,等等等问题 ,这个都可以进行一下完善