Unity中EventManager事件管理器实现方式详解

发表于2018-05-18
评论0 7.2k浏览
上一篇给大家介绍了可以使用EventManager消息管理类处理各种事件,本篇就要和大家介绍下Unity事件管理器的两种实现方式了,第一种采用Unity事件系统API来实现,另一种可以使用C#的事件机制实现。对于这两种实现方式的详细分析如下:

第一种:采用Unity事件系统API来实现
这里的实现采用的是Unity官方教程的实现方式,采用的是单例模式。
using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using UnityEngine.Events;  
public class EventManager  
{  
    private Dictionary<string, UnityEvent> eventDictionary=new Dictionary<string, UnityEvent>();  
    private static EventManager eventManager = new EventManager();  
    private EventManager()  
    {  
    }  
    public static EventManager GetInstance  
    {  
        get  
        {  
            return eventManager;  
        }  
    }  
    public void StartListening(string eventName, UnityAction listener)  
    {  
        UnityEvent thisEvent = null;  
        if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))  
        {  
            thisEvent.AddListener(listener);  
        }  
        else  
        {  
            thisEvent = new UnityEvent();  
            thisEvent.AddListener(listener);  
            eventManager.eventDictionary.Add(eventName, thisEvent);  
        }  
    }  
    public void StopListening(string eventName, UnityAction listener)  
    {  
        if (eventManager == null) return;  
        UnityEvent thisEvent = null;  
        if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))  
        {  
            thisEvent.RemoveListener(listener);  
        }  
    }  
    public void TriggerEvent(string eventName)  
    {  
        UnityEvent thisEvent = null;  
        if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))  
        {  
            thisEvent.Invoke();  
        }  
    }  
}  

事件注册:
using UnityEngine;  
using UnityEngine.Events;  
using System.Collections;  
public class EventTest : MonoBehaviour  
{  
    private UnityAction someListener;    
    void Awake()  
    {  
        someListener = new UnityAction(SomeFunction);  
    }  
    void OnEnable()  
    {  
        EventManager.GetInstance.StartListening("test", someListener);  
        EventManager.GetInstance.StartListening("Spawn", SomeOtherFunction);  
        EventManager.GetInstance.StartListening("Destroy", SomeThirdFunction);  
    }  
    void OnDisable()  
    {  
        EventManager.GetInstance.StopListening("test", someListener);  
        EventManager.GetInstance.StopListening("Spawn", SomeOtherFunction);  
        EventManager.GetInstance.StopListening("Destroy", SomeThirdFunction);  
    }  
    void SomeFunction()  
    {  
        Debug.Log("Some Function was called!");  
    }  
    void SomeOtherFunction()  
    {  
        Debug.Log("Some Other Function was called!");  
    }  
    void SomeThirdFunction()  
    {  
        Debug.Log("Some Third Function was called!");  
    }  
}  

事件触发:
using UnityEngine;  
using System.Collections;  
public class EventTriggerTest : MonoBehaviour  
{  
    void Update()  
    {  
        if (Input.GetKeyDown("q"))  
        {  
            EventManager.GetInstance.TriggerEvent("test");  
        }  
        if (Input.GetKeyDown("o"))  
        {  
            EventManager.GetInstance.TriggerEvent("Spawn");  
        }  
        if (Input.GetKeyDown("p"))  
        {  
            EventManager.GetInstance.TriggerEvent("Destroy");  
        }  
        if (Input.GetKeyDown("x"))  
        {  
            EventManager.GetInstance.TriggerEvent("Junk");  
        }  
    }  
}  

第二种:通过C#事件机制实现
首先定义事件参数和事件
using System;  
using System.Collections.Generic;  
public class EventArg: EventArgs  
{  
    public string ArgName;  
    public Event_CallBack CallBack;  
}  
public delegate void Event_CallBack(object _data = null);  
然后定义事件管理器  
using System;  
using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using UnityEngine.Events;  
public class EventManager  
{  
    //private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>();  
    /// <summary>    
    /// 事件缓存    
    /// </summary>    
    private List<EventArg> callbackList = new List<EventArg>();  
    private static EventManager eventManager = new EventManager();  
    private EventManager()  
    {  
    }  
    public static EventManager GetInstance  
    {  
        get  
        {  
            return eventManager;  
        }  
    }  
    /// <summary>  
    /// 添加事件监听  
    /// </summary>  
    /// <param name="eventName"></param>  
    /// <param name="listener"></param>  
    public void StartListening(string eventName, Event_CallBack listener)  
    {  
        EventArg eventarg = callbackList.Find(a => a.ArgName == eventName);;         
        if (eventarg==null)  
        {  
            eventarg = new EventArg();  
            eventarg.ArgName = eventName;  
            eventarg.CallBack = listener;  
            callbackList.Add(eventarg);  
        }  
        else  
        {  
            eventarg.CallBack += listener;  
        }  
    }  
    /// <summary>  
    /// 移除事件监听  
    /// </summary>  
    /// <param name="eventName"></param>  
    /// <param name="listener"></param>  
    public void StopListening(string eventName, Event_CallBack listener)  
    {  
        EventArg eventarg = callbackList.Find(a => a.ArgName == eventName); ;  
        if (eventarg != null)  
        {  
            eventarg.CallBack -= listener;//移除监听    
            if (eventarg.CallBack == null)//该类型是否还有回调,如果没有,移除    
                callbackList.Remove(eventarg);  
        }  
    }  
    /// <summary>  
    /// 触发事件  
    /// </summary>  
    /// <param name="eventName"></param>  
    public void TriggerEvent(string eventName,object sender)  
    {  
        EventArg eventarg = callbackList.Find(a => a.ArgName == eventName); ;  
        if (eventarg == null)  
        {  
        }  
        else  
        {  
            eventarg.CallBack(sender);//传入参数,执行回调    
        }  
    }  
}  

然后订阅事件
using UnityEngine;  
using UnityEngine.Events;  
using System.Collections;  
using System;  
public class EventTest : MonoBehaviour  
{  
    private Event_CallBack someListener;  
    void Awake()  
    {  
        someListener = new Event_CallBack(SomeFunction);  
    }  
    void OnEnable()  
    {  
        EventManager.GetInstance.StartListening("test", someListener);  
        EventManager.GetInstance.StartListening("Spawn", SomeOtherFunction);  
        EventManager.GetInstance.StartListening("Destroy", SomeThirdFunction);  
    }  
    void OnDisable()  
    {  
        EventManager.GetInstance.StopListening("test", someListener);  
        EventManager.GetInstance.StopListening("Spawn", SomeOtherFunction);  
        EventManager.GetInstance.StopListening("Destroy", SomeThirdFunction);  
    }  
    void SomeFunction(object sender)  
    {  
        Debug.Log("Some Function was called!");  
    }  
    void SomeOtherFunction(object sender)  
    {  
        Debug.Log("Some Other Function was called!");  
    }  
    void SomeThirdFunction(object sender)  
    {  
        Debug.Log("Some Third Function was called!");  
    }  
}  

最后触发事件
using UnityEngine;  
using System.Collections;  
public class EventTriggerTest : MonoBehaviour  
{  
    void Update()  
    {  
        if (Input.GetKeyDown("q"))  
        {  
            EventManager.GetInstance.TriggerEvent("test",this);  
        }  
        if (Input.GetKeyDown("o"))  
        {  
            EventManager.GetInstance.TriggerEvent("Spawn",this);  
        }  
        if (Input.GetKeyDown("p"))  
        {  
            EventManager.GetInstance.TriggerEvent("Destroy",this);  
        }  
        if (Input.GetKeyDown("x"))  
        {  
            EventManager.GetInstance.TriggerEvent("Junk",this);  
        }  
    }  
}  


如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引