1. 定义事件类型
定义一个枚举来表示不同类型的事件。组织和识别不同的事件。
2. 创建事件参数类
为了让事件携带数据,创建一个通用的事件参数类或者为每个事件类型创建特定的参数类。
3. 实现事件管理器
创建一个EventManager类,用于管理事件的注册、注销和触发。
/****************************************************文件:EventManager.cs作者:Edision日期:#CreateTime#功能:事件管理
*****************************************************/using System;
using System.Collections.Generic;public enum EventType
{PlayerJump,PlayerAttack,ItemCollected,// 添加更多事件类型...
}public interface IEventParam { }public static class EventManager
{private static Dictionary<EventType, Action<IEventParam>> eventDictionary = new Dictionary<EventType, Action<IEventParam>>();public static void RegisterListener<T>(EventType eventType, Action<T> listener) where T : IEventParam{if (!eventDictionary.ContainsKey(eventType)){eventDictionary[eventType] = param => listener((T)param);}}public static void UnregisterListener<T>(EventType eventType) where T : IEventParam{if (eventDictionary.ContainsKey(eventType)){eventDictionary.Remove(eventType);}}public static void TriggerEvent(EventType eventType, IEventParam eventParam){if (eventDictionary.TryGetValue(eventType, out var action) && action != null){action(eventParam);}}
}
/****************************************************文件:PlayerJumpEventArgs.cs作者:Edision日期:#CreateTime#功能:玩家跳跃事件参数
*****************************************************/public class PlayerJumpEventArgs : IEventParam
{public float JumpForce;public PlayerJumpEventArgs(float jumpForce){JumpForce = jumpForce;}
}
使用:
/****************************************************文件:TestEvent.cs作者:Edision日期:#CreateTime#功能:使用代码测试
*****************************************************/using UnityEngine;public class TestEvent : MonoBehaviour
{private void Awake(){// 注册监听器EventManager.RegisterListener<PlayerJumpEventArgs>(EventType.PlayerJump, OnPlayerJump);}private void OnPlayerJump(PlayerJumpEventArgs args){Debug.Log($"Player jumped with force: {args.JumpForce}");}private void Update(){if (Input.GetKeyDown(KeyCode.I)){// 触发事件EventManager.TriggerEvent(EventType.PlayerJump, new PlayerJumpEventArgs(5f));}if (Input.GetKeyDown(KeyCode.O)){// 移除事件EventManager.UnregisterListener<PlayerJumpEventArgs>(EventType.PlayerJump);}}}