Unity简易事件管理系统

简单的时间管理系统,根据名字注册和调用时间,也可以根据名字删除

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventSystemManager
{
    private static EventSystemManager main;
    private OnDesEvent desEvent;
    
    public static EventSystemManager Main
    {
        get
        {
            if (main == null)
            {
                main = new EventSystemManager();
            }

            return main;
        }
    }

    
    private Dictionary<string, Action> Event = new Dictionary<string, Action>();

    public void Send(string message)
    {
        if (Event.ContainsKey(message))
        {
            Event[message]();
        }
    }

    public void AddEvent(GameObject target,string eventName,Action action)
    {
        if (Event.ContainsKey(eventName))
        {
            Event[eventName] += action;
        }
        else
        {
            Event.Add(eventName,action);
        }

        desEvent = target.GetComponent<OnDesEvent>() == null
            ? target.AddComponent<OnDesEvent>()
            : target.GetComponent<OnDesEvent>();
        desEvent.AddDesEvent(eventName,action);
    }

    public void RemoveEvent(string eventName)
    {
        if (Event.ContainsKey(eventName))
        {
            Event.Remove(eventName);
        }
    }

    public void RemoveEvent(string name, Action action)
    {
        if (Event.ContainsKey(name))
        {
            try{Event[name] -= action;}catch{}
            Event.Remove(name);
        }
    }
}

其中引入了另一个比较简单的代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.AI;

public class OnDesEvent : MonoBehaviour
{
    private Dictionary<string, Action> events = new Dictionary<string, Action>();

    public void AddDesEvent(string name,Action action)
    {
        events.Add(name,action);
    }

    private void OnDestroy()
    {
        foreach (KeyValuePair<string,Action> action in events)
        {
            EventSystemManager.Main.RemoveEvent(action.Key,action.Value);
        }
    }
}

 

上一篇:封装addEventListener,removeEventListener指定元素添加事件及兼容问题js


下一篇:Unity按键方法管理系统