纯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));
}
相关推荐
我的巨剑能轻松搅动潮汐2 天前
【UE5】pmx导入UE5,套动作。(防止“气球人”现象。
ue5
windwind20002 天前
UE5 跟踪能力的简单小怪
ue5
Deveuper5 天前
UE5 C+、C++、C# 构造方法区别示例
c++·ue5·c#·ue4
windwind20005 天前
UE5 学习方法的思考
ue5·学习方法
ue星空6 天前
UE材质常用节点
ue5·虚幻·材质·虚幻引擎
Zhichao_977 天前
【UE5 C++课程系列笔记】09——多播委托的基本使用
笔记·ue5
异次元的归来8 天前
UE5的TRS矩阵
线性代数·矩阵·ue5·游戏引擎·unreal engine
电子云与长程纠缠9 天前
UE5编辑器下将RenderTarget输出为UTexture并保存
学习·ue5·编辑器·虚幻
ue星空10 天前
虚幻5描边轮廓材质
ue5·材质
ue星空12 天前
虚幻引擎生存建造系统
ue5·游戏引擎·虚幻·虚幻引擎