Unity 脚本之间的消息传递,事件管理



在游戏中发生了一个事件,我们如何把这个时间通知给其他GameObject:比如游戏中发生了爆炸,我们需要在一定范围内的GameObject都感知到这一事件。有的时候,我们希望摄像机以外的物体不要接到我们这一事件的通知。游戏中丰富多彩的世界正是由通信机制构成的


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventCenter  {

    public delegate void DelCallBack();
    /// 
    /// 《所要监听的类型,监听到以后要执行的委托》
    /// 
    public static Dictionary  m_dDicEventType = new Dictionary();
    /// 
    /// 添加监听
    /// 
    /// 
    /// 
    public static void AddListener(EEventType eventType,DelCallBack handler)
    {
        if (!m_dDicEventType.ContainsKey(eventType))
        {
            m_dDicEventType.Add(eventType,null);
        }
        m_dDicEventType[eventType] += handler;
    }
    /// 
    /// 取消指定的监听
    /// 
    /// 
    /// 
    public static void RemoveListener(EEventType eventType, DelCallBack handler)
    {
        if (m_dDicEventType.ContainsKey(eventType))
        {
            m_dDicEventType[eventType] -= handler;
        }
    }
    /// 
    /// 取消所有的监听
    /// 
    public static void RemoveAllListener()
    {
        m_dDicEventType.Clear();
    }
    /// 
    /// 广播消息
    /// 
    public static void Broadcast(EEventType eventType)
    {
        DelCallBack del;
        if (m_dDicEventType.TryGetValue(eventType,out del))
        {
            if (del!=null)
            {
                del();
            }
        }
    }
}
public enum EEventType
{
   
}
当我们触发事件时 只需要调用广播消息就可以了,这样所有添加了这个事件的监听的方法都会被自动执行。



你可能感兴趣的:(Unity3D,通用代码库)