经过多个版本的迭代,已经趋于成熟,可以通过ArrayList传递参数,只需注册和调用即可
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public struct MainEvent
{
public MonoBehaviour host;
public Action<ArrayList> action;
public MainEvent(MonoBehaviour host, Action<ArrayList> action)
{
this.host = host;
this.action = action;
}
}
public class EventSystemManager
{
private static EventSystemManager main;
public static EventSystemManager Main
{
get
{
if (main == null)
{
main = new EventSystemManager();
}
return main;
}
}
private Dictionary<string, List<MainEvent>> Event = new Dictionary<string, List<MainEvent>>();
private Dictionary<string, List<MainEvent>> ReadyEvent = new Dictionary<string, List<MainEvent>>();
AddReadyEvent();
ClearNull();
if (Event.ContainsKey(message))
{
foreach (MainEvent mainEvent in Event[message])
{
try
{
mainEvent.action(value);
}
catch (Exception error)
{
Debug.LogError("事件管理器消息:" + mainEvent.host.ToString().Split('(')[0] + "在调用" + message + "事件时出现错误。");
Debug.LogError(error);
}
}
}
void AddReadyEvent()
{
foreach(var mainEvent in ReadyEvent)
{
if (!Event.ContainsKey(mainEvent.Key))
{
Event.Add(mainEvent.Key, new List<MainEvent>());
}
foreach (var item in mainEvent.Value)
{
Event[mainEvent.Key].Add(item);
}
}
ReadyEvent.Clear();
}
public void AddEvent(MonoBehaviour target, string eventName, Action<ArrayList> action)
{
ClearNull();
if (!ReadyEvent.ContainsKey(eventName))
{
ReadyEvent.Add(eventName, new List<MainEvent>());
}
ReadyEvent[eventName].Add(new MainEvent(target, action));
}
public void AddEvent(MonoBehaviour target, string eventName, Action action)
{
ClearNull();
Action<ArrayList> mainAction = al => { action(); };
if (!ReadyEvent.ContainsKey(eventName))
{
ReadyEvent.Add(eventName, new List<MainEvent>());
}
ReadyEvent[eventName].Add(new MainEvent(target, mainAction));
}
void ClearNull()
{
Dictionary<string, List<MainEvent>> CopyEvent = Event.ToDictionary(key => key.Key , value => new List<MainEvent>(value.Value));
foreach (var key in CopyEvent)
{
foreach (MainEvent mainEvent in CopyEvent[key.Key])
{
if (mainEvent.host == null)
{
Event[key.Key].Remove(mainEvent);
if (Event[key.Key].Count == 0)
{
Event.Remove(key.Key);
}
}
}
}
}
}