zoukankan      html  css  js  c++  java
  • 事件管理器

    项目开发过程中经常会用到代理事件,为方便管理,避免代码混乱,需要一个总的事件管理器:

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System;
    
    public class EventManager<T> {
        
        private static Dictionary<EventType,List<Action<T>>> eventDic = new Dictionary<EventType,List<Action<T>>>();
    
        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="act"></param>
        public static void AddEvent(EventType type, Action<T> act)
        {
            if (eventDic.ContainsKey(type))
            {
                if(!eventDic[type].Contains(act))
                {
                    eventDic[type].Add(act);
                }
            }else
            {
                List<Action<T>> list = new List<Action<T>>();
                eventDic.Add(type, list);
                list.Add(act);
            }
        }
    
        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="type"></param>
        public static void RemoveEvent(EventType type)
        {
            if (eventDic.ContainsKey(type))
            {
                eventDic.Remove(type);
            }
        }
    
        public static void RemoveEvent(EventType type, Action<T> act)
        {
            if (eventDic.ContainsKey(type))
            {
                if (eventDic[type].Contains(act))
                {
                    eventDic[type].Remove(act);
                }
            }
        }
    
        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        public static void TriggerEvent(EventType type , T data)
        {
            if (eventDic.ContainsKey(type))
            {
                List<Action<T>> list = eventDic[type];
                foreach (var callback in list)
                {
                    callback(data);
                }
            }
        }
    }
    
    public enum EventType
    {
        None = 0,
        Event1 = 1,
        Event2 = 2,
    }
  • 相关阅读:
    APK: 开机自启
    Android Button 三种监听方式
    unity 获取Project面板已选择资源的路径
    unity 自定义Project面板右键菜单
    unity Mathf.Atan2()
    unity/C# 通过反射调用对象的私有方法
    Unity WebGL 去除移动端的警告
    Unity Shader 序列帧动画
    Unity Shader 3种精度的数值类型
    Unity Shader Unity支持的语义
  • 原文地址:https://www.cnblogs.com/zjw007/p/6127212.html
Copyright © 2011-2022 走看看