Unity 事件驱动架构

在 Unity 中,很多人会用 UnityEvent(性能极差、产生大量 GC)或者 Dictionary<Type, Delegate>(有装箱拆箱开销、字典查找开销)来写事件中心。

但如果你追求 极致性能和优雅 ,当今 C# 最强悍的事件总线写法是利用 泛型静态类 。这种写法 不需要字典查找,不需要强转类型,0 GC 产生 !🏆

1. 定义事件(使用 struct 避免 GC)

首先,我们把事件定义为 结构体(struct) 。由于结构体分配在栈(Stack)上,所以每次发布事件时都不会产生任何堆内存垃圾(Zero GC)。

cs 复制代码
// 定义一个玩家死亡事件,里面可以携带任何你需要的数据
public struct PlayerDeathEvent
{
    public string KillerName;
    public int DamageTaken;
}

// 另一个事件例子:获得金币
public struct CoinCollectedEvent
{
    public int Amount;
}
2. 极致性能的 EventBus 核心类

利用 C# 的泛型特性,EventBus<T> 会为每一个不同的 T 生成一个独立的静态类。这就是它不需要字典却能完美分类事件的黑魔法

cs 复制代码
using System;

public static class EventBus<T> where T : struct
{
    // 利用 Action<T> 存储订阅者方法
    private static Action<T> OnEvent;

    // 订阅事件
    public static void Subscribe(Action<T> handler)
    {
        OnEvent += handler;
    }

    // 取消订阅
    public static void Unsubscribe(Action<T> handler)
    {
        OnEvent -= handler;
    }

    // 发布事件
    public static void Publish(T eventMessage)
    {
        OnEvent?.Invoke(eventMessage);
    }
}
3. 发布者(Publisher)如何使用?

现在,Player 的代码变得极其干净,它完全不知道其他系统的存在。

cs 复制代码
using UnityEngine;

public class Player : MonoBehaviour
{
    public void Die()
    {
        Debug.Log("玩家倒下了...");
        
        // 仅仅是发布一个结构体事件,0 GC,极其快速
        EventBus<PlayerDeathEvent>.Publish(new PlayerDeathEvent 
        { 
            KillerName = "大魔王", 
            DamageTaken = 9999 
        });
    }
}
4. 订阅者(Subscriber)如何使用?

各个系统自己管好自己的事情,在初始化时订阅,在销毁时 必须 取消订阅。

cs 复制代码
using UnityEngine;

public class AchievementManager : MonoBehaviour
{
    private void OnEnable()
    {
        // 开启监听
        EventBus<PlayerDeathEvent>.Subscribe(OnPlayerDeath);
    }

    private void OnDisable()
    {
        // ⚠️ 极其重要:对象销毁或禁用时,必须取消监听,否则会导致内存泄漏!
        EventBus<PlayerDeathEvent>.Unsubscribe(OnPlayerDeath);
    }

    private void OnPlayerDeath(PlayerDeathEvent evt)
    {
        Debug.Log($"[成就系统] 记录玩家被 {evt.KillerName} 击杀,承受了 {evt.DamageTaken} 点伤害。");
        // 执行解锁成就等逻辑...
    }
}
相关推荐
17岁的勇气4 小时前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
寂寞的船1 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
寂寞的船3 天前
【Unity知识速递】第8期 IL2CPP 托管堆内存碎片与原生堆交互机制深度解析
unity·游戏引擎·交互
寂寞的船4 天前
【Unity知识速递】第5期 Unity 6.2 深度解析:AI Assistant 登场,World Space UI 与 Sentis 全面升级
人工智能·ui·unity
寂寞的船4 天前
【Unity知识速递】第4期 MCP for Unity:用 AI 自然语言控制编辑器
人工智能·unity·编辑器
淡海水4 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc
寂寞的船4 天前
【Unity知识速递】第6期 URP性能优化完全指南:从内存到GPU的三维调优
unity·性能优化·编辑器
寂寞的船4 天前
【Unity Bug挑战】第10期 SerializeReference 内存泄漏之谜
unity·c#·游戏引擎·bug
tealcwu6 天前
【Unity基础】为什么游戏需要物理按键映射?从 Unity Input Manager 到跨引擎输入设计
java·游戏·unity
tealcwu7 天前
【Unity高级】Unity URP:构建同时支持 2D 与 3D 场景的项目完全指南
3d·unity·游戏引擎