Unity简单事件系统管理

1、创建事件管理类

using System.Collections.Generic;
/// <summary>
/// 自定义事件方法委托
/// </summary>
/// <param name="e"></param>
public delegate void EventDelegateCallBack(EventInfo e);
public class GameEventManager
{
    /// <summary>
    /// 事件管理类总事件存储类
    /// </summary>
    private Dictionary<string, EventDelegateCallBack> _eventDict = new Dictionary<string, EventDelegateCallBack>();
    private static GameEventManager _instance;
    public static GameEventManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new GameEventManager();
            }
            return _instance;
        }
    }

    /// <summary>
    /// 添加特定事件方法入字典中
    /// </summary>
    /// <param name="type"></param>
    /// <param name="call"></param>
    public void AddEvent(string type, EventDelegateCallBack call)
    {
        if (!_eventDict.ContainsKey(type))
        {
            _eventDict[type] = call;
        }
        else
        {
            _eventDict[type] += call;
        }
    }

    /// <summary>
    /// 从字典移除特定事件方法
    /// </summary>
    /// <param name="type"></param>
    /// <param name="call"></param>
    public void RemoveEvent(string type, EventDelegateCallBack call)
    {
        if (_eventDict.ContainsKey(type))
        {
            _eventDict[type] -= call;
            if (_eventDict[type] == null)
            {
                _eventDict.Remove(type);
            }
        }
    }

    /// <summary>
    /// 根据类型派发事件
    /// </summary>
    /// <param name="e"></param>
    public void DispathEvent(EventInfo e)
    {
        if (_eventDict.ContainsKey(e.type) && _eventDict[e.type] != null)
        {
            _eventDict[e.type](e);
        }
    }
    /// <summary>
    /// 移除字典中所有的事件
    /// </summary>
    public void RemoveAllEvent()
    {
        _eventDict.Clear();
    }
}

/// <summary>
/// 事件参数结构体
/// </summary>
public struct EventInfo
{
    public string type;
    public object vaule;
    public EventInfo(string t, object v)
    {
        type = t;
        vaule = v;
    }
}

2、测试使用(游戏启动便会自动添加事件方法OnStartGame,想触发事件,点击S键即可触发事件)

using UnityEngine;

public class UseEventTest : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        GameEventManager.Instance.AddEvent("StarGame", OnStartGame);
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKeyDown(KeyCode.S))
        {
            GameEventManager.Instance.DispathEvent(new EventInfo("StarGame", "Test"));
        }
    }

    public void OnStartGame(EventInfo e)
    {
        if ((string)e.vaule == "Test")
        {
            Debug.Log("启动回调");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36274965/article/details/82258436