纯C++事件

一、创建多播委托类型及对象

1、AUECpp_Sender.h

cpp 复制代码
	//声明一个参数多播委托的类型,一定要F开头
	DECLARE_MULTICAST_DELEGATE_OneParam(FUECpp_Broadcast, int);
	//创建对象
	FUECpp_Broadcast UECpp_Broadcast;

2、AUECpp_Sender.cpp

cpp 复制代码
	//发送广播
	UECpp_Broadcast.Broadcast(FMath::RandRange(0, 100));

二、订阅及取消订阅

1、AUECpp_Receiver.h

cpp 复制代码
protected:
	virtual void BeginPlay() override;

public:
	void OnReceived(int Param);	

2、AUECpp_Receiver.cpp

cpp 复制代码
#include "UECpp_Sender.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/Engine.h"
#include "TimerManager.h"

void AUECpp_Receiver::BeginPlay()
{
	Super::BeginPlay();
	//订阅
	AUECpp_Sender* PlayerPawn = Cast<AUECpp_Sender>(UGameplayStatics::GetPlayerPawn(this, 0));
	FDelegateHandle DelegateHandle = PlayerPawn->UECpp_Broadcast.AddUObject(this, &AUECpp_Receiver::OnReceived);

	//计时器
	FTimerHandle TimerHandle;
	auto Lambda = [PlayerPawn, DelegateHandle, this]()
		{
			//取消订阅
			PlayerPawn->UECpp_Broadcast.Remove(DelegateHandle);
			//取消指定类里所有订阅
			PlayerPawn->UECpp_Broadcast.RemoveAll(this->GetPrivateStaticClass());
			//取消所有订阅
			PlayerPawn->UECpp_Broadcast.Clear();
		};
	GetWorld()->GetTimerManager().SetTimer(TimerHandle, FTimerDelegate::CreateLambda(Lambda), 5.0f, false);
}

void AUECpp_Receiver::OnReceived(int Param)
{
	GEngine->AddOnScreenDebugMessage(INDEX_NONE, 10.0f, FColor::Green, FString::Printf(TEXT("%i"), Param));
}
相关推荐
电子云与长程纠缠20 小时前
UE5.3中通过编辑器工具创建大纲菜单文件夹
java·ue5·编辑器
DBBH1 天前
UE5 第三人称学习之动画 control rig
ue5
UTwelve1 天前
【UE5】一种老派的假反射做法,可以用于移动端,或对反射的速度、清晰度有需求的地方
ue5·虚幻引擎·着色器·虚幻4
UTwelve1 天前
【UE5】可以实时绘制的体积渲染 【第三章 体积纹理绘制 - 3.绘制体积】
ue5
1204157137 肖哥2 天前
UE5.4 PCG基础节点
ue5
DBBH3 天前
UE5 材质篇 1 如何偏移顶点
ue5·材质
孤客网络科技工作室3 天前
虚幻引擎5(UE5)学习教程
java·学习·ue5
暮志未晚Webgl3 天前
105. UE5 GAS RPG 搭建主菜单
ue5
异次元的归来3 天前
UE5相机系统初探(一)
ue5·游戏引擎·camera
DBBH5 天前
UE5 材质篇 0 创建一个材质
ue5