Unity高度解耦和 - 事件的监听与广播系统(Unity2018)

本文深入解析Unity中的事件系统,涵盖事件监听与广播的实现机制,包括无参、单参数及多参数事件的处理方法。通过具体示例展示了如何在游戏开发中使用事件系统,如按钮点击触发文本显示等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建添加监听的方法

CallBcak.cs

public delegate void CallBack();
public delegate void CallBack<T>(T arg);

EventType.cs

public enum EventType
{

}

EventCenter.cs

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

public class EventCenter
{
    private static Dictionary<EventType, Delegate> m_EventTable = new Dictionary<EventType, Delegate>();

    //no parameters
    public static void AddListener(EventType eventType,CallBack callBack)
    {
        if(!m_EventTable.ContainsKey(eventType))//如果我们的时间表里不包含事件码
        {
            m_EventTable.Add(eventType, null);
        }
        Delegate d = m_EventTable[eventType];
        if(d!=null && d.GetType() != callBack.GetType())
        {
            throw new Exception(string.Format("尝试为时间{0}添加不同类型的委托,当前事件所对应的委托是{1},要添加的委托的类型为{2}", eventType, d.GetType(), callBack.GetType()));
        }
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] + callBack;
    }
}

移除监听和广播

    //no parameters
    public static void RemoveListener(EventType eventType, CallBack callBack)
    {
        if (m_EventTable.ContainsKey(eventType))
        {
            Delegate d = m_EventTable[eventType];
            if(d == null)
            {
                throw new Exception(string.Format("移除监听错误:事件{0}没有对应的委托", eventType));
            }
            else if (d.GetType() != callBack.GetType())
            {
                throw new Exception(string.Format("移除监听错误:尝试为事件{0}移除不同类型的委托,当前类型的委托类型为{1},要移除的委托类型为{2}", eventType,d.GetType(),callBack.GetType()));
            }
        }
        else
        {
            throw new Exception(string.Format("移除监听错误:没有时间码{0}", eventType));
        }
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] - callBack;
    }

    //no parameters
    public static void Broadcast(EventType eventType)
    {
        Delegate d;
        if(m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack callBack = d as CallBack;
            if(callBack != null)
            {
                callBack();
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

创建测试的脚本,测试无参的监听与广播

首先创建一个Text,给它身上挂一个ShowText脚本

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

public class ShowText : MonoBehaviour
{
    private void Awake()
    {
        gameObject.SetActive(false);
        EventCenter.AddListener(EventType.ShowText, Show);
    }

    private void OnDestroy()
    {
        EventCenter.RemoveListener(EventType.ShowText, Show);
    }

    private void Show()
    {
        gameObject.SetActive(true);
    }
}

然后创建一个按钮,挂一个BtnClick脚本

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

public class BtnClick : MonoBehaviour
{
    private void Awake()
    {
        GetComponent<Button>().onClick.AddListener(() =>
        {
            EventCenter.Broadcast(EventType.ShowText);

        });
    }
}

实现带有一个参数的监听和广播的方法

    //Single Parameter
    public static void AddListener<T>(EventType eventType, CallBack<T> callBack)
    {
        if (!m_EventTable.ContainsKey(eventType))//如果我们的时间表里不包含事件码
        {
            m_EventTable.Add(eventType, null);
        }
        Delegate d = m_EventTable[eventType];
        if (d != null && d.GetType() != callBack.GetType())
        {
            throw new Exception(string.Format("尝试为时间{0}添加不同类型的委托,当前事件所对应的委托是{1},要添加的委托的类型为{2}", eventType, d.GetType(), callBack.GetType()));
        }
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] + callBack;
    }


    //Single parameter
    public static void RemoveListener<T>(EventType eventType, CallBack<T> callBack)
    {
        if (m_EventTable.ContainsKey(eventType))
        {
            Delegate d = m_EventTable[eventType];
            if (d == null)
            {
                throw new Exception(string.Format("移除监听错误:事件{0}没有对应的委托", eventType));
            }
            else if (d.GetType() != callBack.GetType())
            {
                throw new Exception(string.Format("移除监听错误:尝试为事件{0}移除不同类型的委托,当前类型的委托类型为{1},要移除的委托类型为{2}", eventType, d.GetType(), callBack.GetType()));
            }
        }
        else
        {
            throw new Exception(string.Format("移除监听错误:没有时间码{0}", eventType));
        }
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] - callBack;
    }

    //Single parameter
    public static void Broadcast<T>(EventType eventType, T arg)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T> callBack = d as CallBack<T>;
            if (callBack != null)
            {
                callBack(arg);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

在ShowText中也要进行修改

    private void Awake()
    {
        gameObject.SetActive(false);
        EventCenter.AddListener<string>(EventType.ShowText, Show);
        EventCenter.AddListener(EventType.ShowText, Show2);
    }

    private void OnDestroy()
    {
        EventCenter.RemoveListener<string>(EventType.ShowText, Show);
        EventCenter.RemoveListener(EventType.ShowText, Show2);
    }

    private void Show(string str)
    {
        gameObject.SetActive(true);
        GetComponent<Text>().text = str;
    }

实现多个参数的监听和广播

CallBack里面添加多参数

public delegate void CallBack();
public delegate void CallBack<T>(T arg);
public delegate void CallBack<T,X>(T arg1,X arg2);
public delegate void CallBack<T, X,Y>(T arg1, X arg2,Y arg3);
public delegate void CallBack<T, X, Y, Z>(T arg1, X arg2, Y arg3, Z arg4);
public delegate void CallBack<T, X, Y, Z, W>(T arg1, X arg2, Y arg3, Z arg4, W arg5);

添加EventSystem里面的多个参数的方法

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

public class EventCenter
{
    private static Dictionary<EventType, Delegate> m_EventTable = new Dictionary<EventType, Delegate>();

    #region AddListener
    private static void OnListererAdding(EventType eventType,Delegate callBack)
    {
        if (!m_EventTable.ContainsKey(eventType))//如果我们的时间表里不包含事件码
        {
            m_EventTable.Add(eventType, null);
        }
        Delegate d = m_EventTable[eventType];
        if (d != null && d.GetType() != callBack.GetType())
        {
            throw new Exception(string.Format("尝试为时间{0}添加不同类型的委托,当前事件所对应的委托是{1},要添加的委托的类型为{2}", eventType, d.GetType(), callBack.GetType()));
        }
    }

    //no parameters
    public static void AddListener(EventType eventType,CallBack callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] + callBack;
    }

    //Single Parameter
    public static void AddListener<T>(EventType eventType, CallBack<T> callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] + callBack;
    }

    //Two Parameters
    public static void AddListener<T,X>(EventType eventType, CallBack<T,X> callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T,X>)m_EventTable[eventType] + callBack;
    }

    //Three Parameters
    public static void AddListener<T, X,Y>(EventType eventType, CallBack<T, X, Y> callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y>)m_EventTable[eventType] + callBack;
    }

    //Four Parameters
    public static void AddListener<T, X,Y,Z>(EventType eventType, CallBack<T, X, Y, Z> callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z>)m_EventTable[eventType] + callBack;
    }

    //Five Parameters
    public static void AddListener<T, X, Y, Z,W>(EventType eventType, CallBack<T, X, Y, Z, W> callBack)
    {
        OnListererAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z, W>)m_EventTable[eventType] + callBack;
    }

    #endregion

    #region RemoveListener
    private static void OnListenerRemoving(EventType eventType, Delegate callBack)
    {
        if (m_EventTable.ContainsKey(eventType))
        {
            Delegate d = m_EventTable[eventType];
            if (d == null)
            {
                throw new Exception(string.Format("移除监听错误:事件{0}没有对应的委托", eventType));
            }
            else if (d.GetType() != callBack.GetType())
            {
                throw new Exception(string.Format("移除监听错误:尝试为事件{0}移除不同类型的委托,当前类型的委托类型为{1},要移除的委托类型为{2}", eventType, d.GetType(), callBack.GetType()));
            }
        }
        else
        {
            throw new Exception(string.Format("移除监听错误:没有时间码{0}", eventType));
        }
    }

    private static void OnListenerRemoved(EventType eventType)
    {
        if (m_EventTable[eventType] == null)
        {
            m_EventTable.Remove(eventType);
        }
    }

    //no parameters
    public static void RemoveListener(EventType eventType, CallBack callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
 
    //Single parameter
    public static void RemoveListener<T>(EventType eventType, CallBack<T> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }

    //Two parameters
    public static void RemoveListener<T,X>(EventType eventType, CallBack<T,X> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T,X>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }

    //Three parameters
    public static void RemoveListener<T, X,Y>(EventType eventType, CallBack<T, X, Y> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }

    //Four parameters
    public static void RemoveListener<T, X, Y,Z>(EventType eventType, CallBack<T, X, Y, Z> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }

    //Five parameters
    public static void RemoveListener<T, X, Y, Z,W>(EventType eventType, CallBack<T, X, Y, Z, W> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack< T, X, Y, Z, W>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    #endregion

    #region Boradcast
    //no parameters
    public static void Broadcast(EventType eventType)
    {
        Delegate d;
        if(m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack callBack = d as CallBack;
            if(callBack != null)
            {
                callBack();
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

    //Single parameter
    public static void Broadcast<T>(EventType eventType, T arg)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T> callBack = d as CallBack<T>;
            if (callBack != null)
            {
                callBack(arg);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

    //Two parameter
    public static void Broadcast<T,X>(EventType eventType, T arg1, X arg2)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T,X> callBack = d as CallBack<T,X>;
            if (callBack != null)
            {
                callBack(arg1,arg2);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

    //Three parameters
    public static void Broadcast<T, X,Y>(EventType eventType, T arg1, X arg2,Y arg3)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y> callBack = d as CallBack<T, X, Y>;
            if (callBack != null)
            {
                callBack(arg1, arg2,arg3);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }

    //Four parameters
    public static void Broadcast<T, X, Y,Z>(EventType eventType, T arg1, X arg2, Y arg3,Z arg4)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y, Z> callBack = d as CallBack<T, X, Y, Z>;
            if (callBack != null)
            {
                callBack(arg1, arg2, arg3,arg4);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }


    //Five parameters
    public static void Broadcast<T, X, Y, Z,W>(EventType eventType, T arg1, X arg2, Y arg3, Z arg4,W arg5)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y, Z, W> callBack = d as CallBack<T, X, Y, Z,W>;
            if (callBack != null)
            {
                callBack(arg1, arg2, arg3, arg4,arg5);
            }
            else
            {
                throw new Exception(string.Format("广播事件错误:事件{0}对应委托具有不同的类型", eventType));
            }
        }
    }
    #endregion


}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值