简单的事件管理系统,根据名字注册和调用事件,也可以根据名字删除
using System;
using System.Collections.Generic;
using UnityEngine;
public struct MainEvent
{
public GameObject host;
public Action action;
public MainEvent(GameObject host,Action 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,int> waitSend = new Dictionary<string, int>();
public bool Send(string message)
{
ClearNull();
if (Event.ContainsKey(message))
{
try
{
foreach (MainEvent mainEvent in Event[message])
{
mainEvent.action();
}
return true;
}
catch(Exception error)
{
Debug.LogError(error);
return true;
}
}
return false;
}
public void AddEvent(GameObject target,string eventName,Action action)
{
ClearNull();
if (waitSend.ContainsKey(eventName))
{
for (int i = 0; i < waitSend[eventName]; i++)
{
action();
}
waitSend.Remove(eventName);
}
if (!Event.ContainsKey(eventName))
{
Event.Add(eventName,new List<MainEvent>());
}
Event[eventName].Add(new MainEvent(target,action));
}
public bool ContainsEvent(GameObject target,string eventName)
{
ClearNull();
if (Event.ContainsKey(eventName))
{
foreach (MainEvent mainEvent in Event[eventName])
{
if (mainEvent.host == target)
{
return true;
}
}
}
return false;
}
public void RemoveEvent(GameObject target)
{
two:foreach (var key in Event)
{
one:foreach (MainEvent mainEvent in Event[key.Key])
{
if (mainEvent.host == target)
{
Event[key.Key].Remove(mainEvent);
goto one;
}
}
if (key.Value.Count == 0)
{
Event.Remove(key.Key);
goto two;
}
}
}
public void RemoveEvent(GameObject target,string eventName)
{
two:foreach (var key in Event)
{
if (key.Key != eventName)
{
continue;
}
one:foreach (MainEvent mainEvent in Event[key.Key])
{
if (mainEvent.host == target)
{
Event[key.Key].Remove(mainEvent);
goto one;
}
}
if (key.Value.Count == 0)
{
Event.Remove(key.Key);
goto two;
}
}
}
public void WaitSend(string name)
{
if(Send(name)){return;}
if (waitSend.ContainsKey(name))
{
waitSend[name] += 1;
}
else
{
waitSend.Add(name,1);
}
}
void ClearNull()
{
two:foreach (var key in Event)
{
one:foreach (MainEvent mainEvent in Event[key.Key])
{
if (mainEvent.host == null)
{
Event[key.Key].Remove(mainEvent);
goto one;
}
}
if (key.Value.Count == 0)
{
Event.Remove(key.Key);
goto two;
}
}
}
}