欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > DeepSeek教unity------事件管理

DeepSeek教unity------事件管理

2025/2/22 16:56:41 来源:https://blog.csdn.net/Edision_li/article/details/145705018  浏览:    关键词:DeepSeek教unity------事件管理

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);}}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词