EventManager的两种简单实现方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010989951/article/details/79051299

在进行unity相关开发过程中我们总是要响应很多事件,如果没有一个集中的管理,那么代码就会变得很混乱,这时EventManager就变得很需了。Unity事件管理器可以有两种方式实现,第一种是调用Unity的事件系统来进行封装,另一种可以使用C#的事件与委托机制实现,两种方式其实都很简单,也各有优缺点,具体的性能差异这篇文章已经总结的很好了http://blog.csdn.net/su9257/article/details/53679739。这里我只说明实现方式,具体实现如下:

第一种:采用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);
        }
    }
}







展开阅读全文

没有更多推荐了,返回首页