[Unity3D]簡單的事件管理器

一個簡單的事件管理器
任意一個枚舉就可以定義事件類型。

using System.Collections.Generic;
using System;
public enum GameEvent
{
    StartGame,
    GameOver,
}

public class EventMgr<T> 
{
    private static EventMgr<T> _instance;
    public static EventMgr<T> instance
    {
        get
        {
            if(_instance==null)
            {
                _instance = new EventMgr<T>();
            }
            return _instance;
        }
    }
    private Dictionary<T, Action<object[]>> eventDict;
    private EventMgr()
    {
        eventDict = new Dictionary<T, Action<object[]>>();
    }

    public void TriggerEvent(T eventName,params object[] param)
    {
        if(eventDict.ContainsKey(eventName))
        {
            eventDict[eventName](param);
        }
    }
    public void AddListener(T eventName,Action<object[]> cb)
    {
        if(eventDict.ContainsKey(eventName))
        {
            eventDict[eventName] += cb;
        }
        else
        {
            eventDict[eventName] = cb;
        }

    }
    public void RemListener(T eventName, Action<object[]> cb)
    {
        if(eventDict.ContainsKey(eventName))
        {
            eventDict[eventName] -= cb;
        }

    }
}

使用試例:

 // 監聽事件                
 EventMgr<GameEvent>.instance.AddListener(GameEvent.StartGame, OnGameStart);
 // 移除監聽
 EventMgr<GameEvent>.instance.RemListener(GameEvent.StartGame, OnGameStart);
 //觸發事件
                 EventMgr<GameEvent>.instance.TriggerEvent(GameEvent.StartGame, "test");
 //事件接接收方法
private void OnGameStart(object[] param)
{
	string msg = param[0] as string;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章