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

来源:互联网 发布:数据库系统的二级映射 编辑:程序博客网 时间:2024/06/05 08:43


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


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



原创粉丝点击