最近在研究廣播系統,寫下來記錄一下,好記性不如爛筆頭。簡單寫了無參數廣播事件系統
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void CallBack();//需要有參數的直接在這加上需要的參數就可以實現參數廣播。
public enum EventTypee//廣播事件
{
test
}
public class EventCenter : MonoBehaviour
{
private static Dictionary<EventTypee, Delegate> dic = new Dictionary<EventTypee, Delegate>();
/// <summary>
/// 添加事件監聽
/// </summary>
/// <param name="eventType"></param>
/// <param name="callBack"></param>
public static void AddListener(EventTypee eventTypee,CallBack callBack)
{
if (!dic.ContainsKey(eventTypee))
{
dic.Add(eventTypee, null);
}
//異常拋出
Delegate m = dic[eventTypee];
if (m != null && m.GetType() != callBack.GetType())
{
throw new Exception(string.Format("事件{0}爲不同委託,對應爲{1},添加類型爲{2}", eventTypee, m.GetType(), callBack.GetType()));
}
dic[eventTypee] = (CallBack)dic[eventTypee] + callBack;
}
/// <summary>
/// 移除監聽事件
/// </summary>
/// <param name="eventTypee"></param>
/// <param name="callBack"></param>
public static void RemoveListener(EventTypee eventTypee,CallBack callBack)
{
//異常拋出
if (dic.ContainsKey(eventTypee))
{
Delegate m = dic[eventTypee];
if(m == null)
{
throw new Exception(string.Format("錯誤;事件{0}沒有添加", eventTypee));
}
else if (m.GetType()!= callBack.GetType())
{
throw new Exception(string.Format("移除錯誤,事件{0}於事件{1}爲不同委託", m.GetType(), callBack.GetType()));
}
}
else
{
throw new Exception(string.Format("錯誤,沒有事件{0}", eventTypee));
}
dic[eventTypee] = (CallBack)dic[eventTypee] - callBack;
if (dic[eventTypee] == null)
{
dic.Remove(eventTypee);
}
}
/// <summary>
/// 事件的廣播
/// </summary>
/// <param name="eventTypee"></param>
public static void Broadcast(EventTypee eventTypee)
{
Delegate m;
if (dic.TryGetValue(eventTypee, out m))
{
CallBack callBack = m as CallBack;
if(callBack != null)
{
callBack();
}
else
{
throw new Exception(string.Format("錯誤,事件已存在", eventTypee));
}
}
}
}
測試一下
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private void Awake()
{
EventCenter.AddListener(EventTypee.test, Show1);
}
private void Show1()
{
Debug.Log("廣播成功");
}
private void OnDestroy()
{
EventCenter.RemoveListener(EventTypee.test, Show1);
}
public void OnShowBtnClick()
{
EventCenter.Broadcast(EventTypee.test);
}
}