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


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值