纯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));
}
相关推荐
妙为10 小时前
ue5 仿鬼泣5魂类游戏角色和敌人没有碰撞
游戏·ue5·碰撞
努力的小钟15 小时前
Unreal Engine 高效数组复制用法详解
ue5·游戏引擎·虚幻
Zhichao_971 天前
【UE5 C++课程系列笔记】32——读Json文件并解析
c++·ue5
吴梓穆1 天前
UE5学习笔记 FPS游戏制作42 按钮添加回调函数
笔记·学习·ue5
沾血滴蔷薇1 天前
虚幻5入门
数码相机·ue5
吴梓穆1 天前
UE5学习笔记 FPS游戏制作39 制作一个带有背景的预制面板 使用overlay和nameSlot
笔记·学习·ue5
AgilityBaby1 天前
UE5把动画导出为视频格式
ue5·游戏引擎·unreal engine
远离UE42 天前
UE5 Simulation Stage
ue5
吴梓穆2 天前
UE5学习笔记 FPS游戏制作38 继承标准UI
笔记·学习·ue5
蛋卷卷-2 天前
【UE5】发现意外的文件尾解决方法
ue5