Unity_基于观察者模式的事件中心模块

小鸟游星野
小鸟游星野
发布于 2025-03-13 / 42 阅读
0
0

Unity_基于观察者模式的事件中心模块

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

public abstract class ObjBase
{
    
}

public class TypeAction<T>: ObjBase
{
    public TypeAction(UnityAction<T> action)
    {
        this.action += action;
    }
    public UnityAction<T> action;
}

public class TypeAction : ObjBase
{
    public TypeAction(UnityAction action)
    {
        this.action += action;
    }
    public UnityAction action;
}
public class EventCenter : NoMonoSingleton<EventCenter>
{
    private EventCenter()
    {
        
    }
    /// <summary>
    /// 用string记录事件名称 比如怪物死亡就会去调用该名称事件的委托函数
    /// 个个观察者将自己要执行的方法压入我们的委托当中
    /// </summary>
    public Dictionary<string, ObjBase> events = new Dictionary<string, ObjBase>();
    
    
    
    //为被观察者提供触发委托的方法
    public void EventTrigger<T>(string eventName,T param)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction<T>).action?.Invoke(param);
        }
    }

    public void EventTrigger(string eventName)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction).action?.Invoke();
        }
    }
    //为观察者准备的增加方法
    public void AddAction<T>(string eventName, UnityAction<T> action)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction<T>).action += action;
        }
        else
        {
            //先创建字典
            events.Add(eventName,new TypeAction<T>(action));
        }
    }

    public void AddAction(string eventName, UnityAction action)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction).action += action;
        }
        else
        {
            //先创建字典
            events.Add(eventName,new TypeAction(action));
        }
    }
    
    //当观察者不需要观察时移除多余委托内容的方法
    public void RemoveAction<T>(string eventName, UnityAction<T> action)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction<T>).action -= action;
        }
    }

    public void RemoveAction(string eventName, UnityAction action)
    {
        if (events.ContainsKey(eventName))
        {
            (events[eventName] as TypeAction).action -= action;
        }
    }
    
    
    //清空具体委托
    public void ClearAction(string eventName)
    {
        if (events.ContainsKey(eventName))
        {
            events.Remove(eventName);
        }
    }
    //清空全体委托
    public void ClearAction()
    {
        events.Clear();
    }
}


评论