unity简易事件分发器
一、EventFunction
using System; namespace EventCore { public struct EventFunction { public object _caller; public Action _action; } public struct EventFunction<T> { public object _caller; public Action<T> _action; } }
二、Event<T>
using System; using System.Collections.Generic; using UnityEngine; namespace EventCore { public class Event<T> { private readonly List<EventFunction<T>> _event = new List<EventFunction<T>>(); public void AddListener(object caller, Action<T> action) { if (action != null) { for (int index = 0, max = _event.Count; index < max; index++) { var element = _event[index]; if (element._caller == caller && element._action == action) { Debug.LogError("EventGeneric,重复添加事件:" + element._caller + "," + element._action.Method); return; } } } _event.Add(new EventFunction<T> { _caller = caller, _action = action }); } public void RemoveListener(object caller, Action<T> action) { for (int index = _event.Count - 1; index >= 0; index--) { var element = _event[index]; if (element._caller == caller && element._action == action) { _event.RemoveAt(index); return; } } } public void Trigger(T data) { for (int index = _event.Count - 1; index >= 0; index--) { var element = _event[index]; if (element._action != null) { element._action(data); } else { Debug.LogError("EventGeneric: event removed"); } } } } }
三、Event
using System; using System.Collections.Generic; using UnityEngine; namespace EventCore { public class Event { private readonly List<EventFunction> _event = new List<EventFunction>(); public void AddListener(object caller, Action action) { if (action != null) { for (int index = 0, max = _event.Count; index < max; index++) { var element = _event[index]; if (element._caller == caller && element._action == action) { Debug.LogError("EventGeneric,重复添加事件:" + element._caller + "," + element._action.Method); return; } } } _event.Add(new EventFunction { _caller = caller, _action = action }); } public void RemoveListener(object caller, Action action) { for (int index = _event.Count - 1; index >= 0; index--) { var element = _event[index]; if (element._caller == caller && element._action == action) { _event.RemoveAt(index); return; } } } public void Trigger() { for (int index = _event.Count - 1; index >= 0; index--) { var element = _event[index]; if (element._action != null) { element._action(); } else { Debug.LogError("EventGeneric: event removed"); } } } } }
四、使用分发器
事件定义:
using EventCore; public class TestEvent { public static Event<int> TestEvent1 = new Event<int>(); // 事件测试 public static Event TestEvent2 = new Event(); // 事件测试 }
事件注册、事件注销:
TestEvent.TestEvent2.AddListener(this, OnTestEvent); TestEvent.TestEvent2.RemoveListener(this, OnTestEvent); private void OnTestEvent() { }
事件触发:
TestEvent.TestEvent2.Trigger();

浙公网安备 33010602011771号