美文网首页
unity简单消息监听

unity简单消息监听

作者: RichMartin | 来源:发表于2020-04-17 15:32 被阅读0次
    using UnityEngine;
    using UnityEngine.Events;
    using System.Collections;
    using System.Collections.Generic;
    
    public class EventManager : MonoBehaviour {
    
        private Dictionary <string, UnityEvent> eventDictionary;
    
        private static EventManager eventManager;
    
        public static EventManager instance
        {
            get
            {
                if (!eventManager)
                {
                    eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;
    
                    if (!eventManager)
                    {
                        Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
                    }
                    else
                    {
                        eventManager.Init (); 
                    }
                }
    
                return eventManager;
            }
        }
    
        void Init ()
        {
            if (eventDictionary == null)
            {
                eventDictionary = new Dictionary<string, UnityEvent>();
            }
        }
    
        public static void StartListening (string eventName, UnityAction listener)
        {
            UnityEvent thisEvent = null;
            if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
            {
                thisEvent.AddListener (listener);
            } 
            else
            {
                thisEvent = new UnityEvent ();
                thisEvent.AddListener (listener);
                instance.eventDictionary.Add (eventName, thisEvent);
            }
        }
    
        public static void StopListening (string eventName, UnityAction listener)
        {
            if (eventManager == null) return;
            UnityEvent thisEvent = null;
            if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
            {
                thisEvent.RemoveListener (listener);
            }
        }
    
        public static void TriggerEvent (string eventName)
        {
            UnityEvent thisEvent = null;
            if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
            {
                thisEvent.Invoke ();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:unity简单消息监听

          本文链接:https://www.haomeiwen.com/subject/sjlyvhtx.html