UE 事件分发机制(二) day10

news/2025/3/15 16:33:12/

自定义事件分发机制

自建事件分发机制与结构

  • Unreal推荐的游戏逻辑开发流程
    在这里插入图片描述
  • 基于 Unreal推荐的游戏逻辑开发流程,一般我们的整体规划也就是这样
    在这里插入图片描述
  • 大致结构类图
    在这里插入图片描述

创建接口类与管理类以及所需函数

  • 新建一个Unreal接口类作为接口
    在这里插入图片描述
  • 然后创建一个蓝图函数库的基类
    在这里插入图片描述

EventInterface接口类

EventInterface.h

  • 复习一下BlueprintNativeEvent这个参数:会在C++中提供一个默认的实现,然后蓝图中去覆盖它改写它,在蓝图中实现这个函数时,如果调用一个父类的版本,它会先调用C++里面加了_Implementation这个函数,然后再去做蓝图其他的操作
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "EventInterface.generated.h"// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class UEventInterface : public UInterface
{GENERATED_BODY()
};/*** */
class DISTRIBUTE_API IEventInterface
{GENERATED_BODY()// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:UFUNCTION(BlueprintNativeEvent,Category="Event Dispather Tool")void OnReceiveEvent(UObject* Data);
};

EventInterface.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "EventInterface.h"// Add default functionality here for any IEventInterface functions that are not pure virtual.

EventManager蓝图函数库的基类管理类

EventManager.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "EventManager.generated.h"/*** */
UCLASS()
class DISTRIBUTE_API UEventManager : public UBlueprintFunctionLibrary
{GENERATED_BODY()private://监听者static TMap<FString, TArray<UObject*>> AllListeners;public:UFUNCTION(BlueprintCallable, Category = "Event Dispather Tool")static void AddEventListener(FString EventName, UObject* Listener);UFUNCTION(BlueprintCallable, Category = "Event Dispather Tool")static void RemoveEventListener(FString EventName, UObject* Listener);UFUNCTION(BlueprintCallable, Category = "Event Dispather Tool")static FString  DispatchEvent(FString EventName, UObject* Data);UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Event Dispather Tool")static UObject* NameAsset(UClass* ClassType);
};

EventManager.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "EventManager.h"void UEventManager::AddEventListener(FString EventName, UObject* Listener)
{
}void UEventManager::RemoveEventListener(FString EventName, UObject* Listener)
{
}FString UEventManager::DispatchEvent(FString EventName, UObject* Data)
{return FString();
}UObject* UEventManager::NameAsset(UClass* ClassType)
{return nullptr;
}

编写AddEventListener函数

  • 加入接口的头文件,判断添加进来的事件名字是否为空,监听指针是否为空,检测对象是否有效,是否实现了指定的接口类

  • Listener->IsValidLowLevel():检查对象是否有效

  • Listener->GetClass()->ImplementsInterface(UEventInterface::StaticClass()):检测接口是否实现指定接口,这里传入的UEventInterface就是接口类中的参与蓝图的类名
    在这里插入图片描述

    //初始化监听器
    TMap<FString, TArray<UObject*>> UEventManager::AllListeners;void UEventManager::AddEventListener(FString EventName, UObject* Listener)
    {if (EventName == "" || Listener == nullptr || !Listener->IsValidLowLevel() ||!Listener->GetClass()->ImplementsInterface(UEventInterface::StaticClass())){return;}
    }
    
  • 然后查找是否存在这个事件数组,如果为空说明目前没有这个事件,就重新添加一下,存在就直接添加事件进入到数组即可

  • AddEventListener函数完整代码逻辑

#include "EventManager.h"
#include "EventInterface.h"//初始化监听器
TMap<FString, TArray<UObject*>> UEventManager::AllListeners;void UEventManager::AddEventListener(FString EventName, UObject* Listener)
{if (EventName == "" || Listener == nullptr || !Listener->IsValidLowLevel() ||!Listener->GetClass()->ImplementsInterface(UEventInterface::StaticClass())){return;}//查找是否存在这个事件数组TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);//如果为空说明目前没有这个事件,就重新添加一下if (EventArr == nullptr || EventArr->Num() == 0){TArray<UObject*> NewEventArr = { Listener };UEventManager::AllListeners.Add(EventName, NewEventArr);}//存在就直接添加事件进入到数组即可else{EventArr->Add(Listener);}
}

编写其他函数

RemoveEventListener函数编写

  • 查询事件数组中是否有这个事件,如果有就删除这个事件
void UEventManager::RemoveEventListener(FString EventName, UObject* Listener)
{TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);if (EventArr != nullptr && EventArr->Num() != 0){EventArr->Remove(Listener);}
}

DispatchEvent函数编写

  • 分派事件,也是首先考虑事件是否存在,然后循环事件数组里事件,不存在的事件就直接剔除,存在的就进行派发事件通知,注意派发事件通知时也要进行安全检测
FString UEventManager::DispatchEvent(FString EventName, UObject* Data)
{TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);//如果不存在此事件数组if (EventArr == nullptr || EventArr->Num() == 0){return "'" + EventName + "'No Listener.";}//使用UE_LOG换行,方便查看FString ErrorInfo = "\n";for (int i = 0; i < EventArr->Num(); i++){UObject* Obj = (*EventArr)[i];//安全判断一下事件是否存在if (Obj == nullptr || !Obj->IsValidLowLevel() || !Obj->GetClass()->ImplementsInterface(UEventInterface::StaticClass())){//不存在直接剔除EventArr->RemoveAt(i);//剔除后要i--,因为TArray删除一个元素后会自动补齐,这样会导致我们当前循环出现bugi--;}//通过了安全检测就直接派遣事件通知else{UFunction* FUN = Obj->FindFunction("OnReceiveEvent");//安全检测这个FUN是否有效if (FUN == nullptr || !FUN->IsValidLowLevel()){//打印错误信息ErrorInfo += "'" + Obj->GetName() + "'No 'OnReceiveEvent' Function.\n";}else{//调用Obj->ProcessEvent(FUN, &Data);}}}return ErrorInfo;
}

NameAsset函数编写

  • 这个函数是方便我们在蓝图中去创建某一个新的指定类实例
  • 加入头文件 #include “Engine.h”,使用NewObject函数来创建一个新的指定对象
  • UObject* Obj = NewObject<UObject>(GetTransientPackage(), ClassType);
    • GetTransientPackage():返回一个临时包(主要用于对象池)的指针
    • ClassType:ClassType 是一个 UClass 指针,指定了新对象的类型。
UObject* UEventManager::NameAsset(UClass* ClassType)
{UObject* Obj = NewObject<UObject>(GetTransientPackage(), ClassType);return Obj;
}

EventManager.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "EventManager.h"
#include "EventInterface.h"
#include "Engine.h"
//初始化监听器
TMap<FString, TArray<UObject*>> UEventManager::AllListeners;void UEventManager::AddEventListener(FString EventName, UObject* Listener)
{if (EventName == "" || Listener == nullptr || !Listener->IsValidLowLevel() ||!Listener->GetClass()->ImplementsInterface(UEventInterface::StaticClass())){return;}//查找是否存在这个事件数组TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);//如果为空说明目前没有这个事件,就重新添加一下if (EventArr == nullptr || EventArr->Num() == 0){TArray<UObject*> NewEventArr = { Listener };UEventManager::AllListeners.Add(EventName, NewEventArr);}//存在就直接添加事件进入到数组即可else{EventArr->Add(Listener);}
}void UEventManager::RemoveEventListener(FString EventName, UObject* Listener)
{TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);if (EventArr != nullptr && EventArr->Num() != 0){EventArr->Remove(Listener);}
}FString UEventManager::DispatchEvent(FString EventName, UObject* Data)
{TArray<UObject*>* EventArr = UEventManager::AllListeners.Find(EventName);//如果不存在此事件数组if (EventArr == nullptr || EventArr->Num() == 0){return "'" + EventName + "'No Listener.";}//使用UE_LOG换行,方便查看FString ErrorInfo = "\n";for (int i = 0; i < EventArr->Num(); i++){UObject* Obj = (*EventArr)[i];//安全判断一下事件是否存在if (Obj == nullptr || !Obj->IsValidLowLevel() || !Obj->GetClass()->ImplementsInterface(UEventInterface::StaticClass())){//不存在直接剔除EventArr->RemoveAt(i);//剔除后要i--,因为TArray删除一个元素后会自动补齐,这样会导致我们当前循环出现bugi--;}//通过了安全检测就直接派遣事件通知else{UFunction* FUN = Obj->FindFunction("OnReceiveEvent");//安全检测这个FUN是否有效if (FUN == nullptr || !FUN->IsValidLowLevel()){//打印错误信息ErrorInfo += "'" + Obj->GetName() + "'No 'OnReceiveEvent' Function.\n";}else{//调用Obj->ProcessEvent(FUN, &Data);}}}return ErrorInfo;
}UObject* UEventManager::NameAsset(UClass* ClassType)
{UObject* Obj = NewObject<UObject>(GetTransientPackage(), ClassType);return Obj;
}

自定义事件分发广播事件

  • 因为我们的自定义事件系统里面发布数据只有一个参数,所以我们新建一个Object类专门来放数据,需要传递数据时就通过这个Object类
    在这里插入图片描述
    在这里插入图片描述
  • 然后创建一个Pawn类作为SenderEvent发起者,开始广播事件
// Called when the game starts or when spawned
void AMyBPAndCpp_Sender::BeginPlay()
{Super::BeginPlay();FTimerHandle TimerHandle;auto Lambda = [](){//开始广播事件UMyData* Data = Cast<UMyData>(UEventManager::NameAsset(UMyData::StaticClass()));Data->Param = FMath::RandRange(0, 100);//委派事件UEventManager::DispatchEvent("MyBPAndCpp_DispatchEvent", Data);};GetWorld()->GetTimerManager().SetTimer(TimerHandle, FTimerDelegate::CreateLambda(Lambda), 3.f, true);}

MyBPAndCpp_Sender.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "MyBPAndCpp_Sender.generated.h"UCLASS()
class DISTRIBUTE_API AMyBPAndCpp_Sender : public APawn
{GENERATED_BODY()public:// Sets default values for this pawn's propertiesAMyBPAndCpp_Sender();UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Properties")class UStaticMeshComponent* StaticMesh;
protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;};

MyBPAndCpp_Sender.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "MyBPAndCpp_Sender.h"
#include "Components/StaticMeshComponent.h"
#include "UObject/ConstructorHelpers.h"
#include "EventDistributeTool/EventManager.h"
#include "Public/TimerManager.h"
#include "MyData.h"// Sets default values
AMyBPAndCpp_Sender::AMyBPAndCpp_Sender()
{// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));RootComponent = StaticMesh;static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialAsset(TEXT("Material'/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial'"));if (StaticMeshAsset.Succeeded() && MaterialAsset.Succeeded()){StaticMesh->SetStaticMesh(StaticMeshAsset.Object);StaticMesh->SetMaterial(0, MaterialAsset.Object);}
}// Called when the game starts or when spawned
void AMyBPAndCpp_Sender::BeginPlay()
{Super::BeginPlay();FTimerHandle TimerHandle;auto Lambda = [](){//开始广播事件UMyData* Data = Cast<UMyData>(UEventManager::NameAsset(UMyData::StaticClass()));Data->Param = FMath::RandRange(0, 100);//委派事件UEventManager::DispatchEvent("MyBPAndCpp_DispatchEvent", Data);};GetWorld()->GetTimerManager().SetTimer(TimerHandle, FTimerDelegate::CreateLambda(Lambda), 3.f, true);}// Called every frame
void AMyBPAndCpp_Sender::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}// Called to bind functionality to input
void AMyBPAndCpp_Sender::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);}

自定义事件分发订阅事件

  • 新建一个Actor基类,然后派生三个子类来订阅事件测试,这三个子类需要继承EventInterface这个接口类,父类接口中方法有BlueprintNativeEvent反射参数,所以在这实现加后缀_Implementation
    在这里插入图片描述

Actor_Receive_R.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "EventDistributeTool/EventInterface.h"
#include "BPAndCpp/Actor_Receive.h"
#include "Actor_Receive_R.generated.h"/*** */
UCLASS()
class DISTRIBUTE_API AActor_Receive_R : public AActor_Receive, public IEventInterface
{GENERATED_BODY()protected:virtual void BeginPlay() override;
public:virtual void OnReceiveEvent_Implementation(UObject* Data) override;
};

Actor_Receive_R.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "Actor_Receive_R.h"
#include "Engine/Engine.h"
#include "MyData.h"
#include "EventDistributeTool/EventManager.h"
void AActor_Receive_R::BeginPlay()
{Super::BeginPlay();//订阅事件UEventManager::AddEventListener("MyBPAndCpp_DispatchEvent", this);
}
void AActor_Receive_R::OnReceiveEvent_Implementation(UObject* Data)
{//打印到屏幕GEngine->AddOnScreenDebugMessage(INDEX_NONE, 10.f, FColor::Red, FString::Printf(TEXT("%i"), Cast<UMyData>(Data)->Param));
}
  • 运行结果
    在这里插入图片描述
  • 触发错误打印log的原因是因为,EventManager类中的都是静态方法,静态方法只有到下次编译之后才会被释放,所以在调试中就会这样触发log
  • 使用在视口中播放就不会触发log,在正式游戏中也不会触发,或者有正常的解绑事件也不会有问题
    在这里插入图片描述

自定义事件分发蓝图订阅与解绑事件

蓝图订阅事件

  • 蓝图订阅事件,创建一个Actor蓝图然后派生三个子蓝图,注意调用接口类中的事件时要添加接口后编译才能找到OnReceiveEvent,然后委派事件时的名字记得填写
    在这里插入图片描述
  • 运行结果
    在这里插入图片描述

解绑事件

  • 解绑调用RemoveEventListener函数即可
    在这里插入图片描述
  • C++中也是差不多调用RemoveEventListener函数即可
    在这里插入图片描述
  • 运行结果,只会播放一轮了
    在这里插入图片描述

当播放结束时自动移除事件

  • 这样也能解决C++中的触发错误打印log
  • 蓝图中结束后自动移除事件
    在这里插入图片描述
  • C++中是重写BeginDestroy函数,调用移除函数即可
    在这里插入图片描述
    在这里插入图片描述
  • 运行结果,这样就不会有log错误了
    在这里插入图片描述

自定义事件之蓝图广播事件

  • 将MyBPAndCpp_Sender类转换为蓝图,首先调用一下父类的BeginPlay这样C++那边的事件才会生效
    在这里插入图片描述
  • 编写蓝图逻辑,发布广播
    在这里插入图片描述
  • 然后找个Actor蓝图接收事件,测试,订阅一下这个事件名即可
    在这里插入图片描述
  • 运行结果
    在这里插入图片描述

http://www.ppmy.cn/news/1249390.html

相关文章

WPF中DataGrid解析

效果如图&#xff1a; 代码如下&#xff1a; <DataGrid Grid.Row"1" x:Name"dataGrid" ItemsSource"{Binding DataList}" AutoGenerateColumns"False"SelectedItem"{Binding SelectedItem,UpdateSourceTriggerPropertyChange…

详解Python中httptools模块的使用

httptools 是一个 HTTP 解析器&#xff0c;它首先提供了一个 parse_url 函数&#xff0c;用来解析 URL。这篇文章就来和大家聊聊它的用法吧&#xff0c;感兴趣的可以了解一下 如果你用过 FastAPI 的话&#xff0c;那么你一定知道 uvicorn&#xff0c;它是一个基于 uvloop 和 h…

@RequestMapping详解:请求映射规则

目录 请求-相应模式&#xff1a; 设置请求映射规则RequestMapping POST 请求&#xff1a; GET 请求 请求-相应模式&#xff1a; 前端作为客户端向后端发送请求&#xff08;请求可以分为请求头和请求体两部分&#xff0c;请求头包含了一些元数据信息&#xff0c;如请求方式、…

炸裂:completablefuture自定义线程池慢2倍......比默认线程池......

尼恩说在前面 尼恩社群中&#xff0c;很多小伙伴找尼恩来卷3高技术&#xff0c;学习3高架构&#xff0c;遇到问题&#xff0c;常常找尼恩反馈和帮扶。 周一&#xff0c;一个5年经验的大厂小伙伴&#xff0c;反馈了一个令人震惊的问题 completablefuture自定义线程池慢2倍…比…

使用Ray轻松进行Python分布式计算

大家好&#xff0c;在实际研究中&#xff0c;即使是具有多个CPU核心的单处理器计算机&#xff0c;也会给人一种能够同时运行多个任务的错觉。当我们拥有多个处理器时&#xff0c;就可以真正以并行的方式执行计算&#xff0c;本文将简要介绍Python分布式计算。 1.并行计算与分布…

【Spring之事务底层源码解析,持续更新中~~~】

文章目录 一、EnableTransactionManagement工作原理二、Spring事务基本执行原理三、Spring事务传播机制与分类四、Spring事务强制回滚五、TransactionSynchronization六、Spring事务详细执行流程 一、EnableTransactionManagement工作原理 二、Spring事务基本执行原理 三、Sp…

文件重命名:如何删除文件名中的下划线,特殊符号批量删除

在日常的工作中&#xff0c;经常会遇到文件名中包含特殊符号的情况&#xff0c;例如&#xff0c;一些文件名可能包含下划线、空格或其他特殊符号&#xff0c;这些符号可能会干扰我们的文件搜索和识别。此外&#xff0c;一些文件名可能包含无法识别的非标准字符&#xff0c;这可…

【MyBatis注解实现模糊查询】

文章目录 1. 准备工作2. 创建数据库表3. 编写Mapper接口4. 编写SQL语句5. 使用注解进行查询6. 示例代码 1. 准备工作 可以参考MyBatis官方文档 2. 创建数据库表 假设有一个名为users的表&#xff0c;包含以下字段&#xff1a; id&#xff08;主键&#xff09;username&…