一、创建多播委托类型及对象
1、AUECpp_Sender.h
//声明一个参数多播委托的类型,一定要F开头
DECLARE_MULTICAST_DELEGATE_OneParam(FUECpp_Broadcast, int);
//创建对象
FUECpp_Broadcast UECpp_Broadcast;
2、AUECpp_Sender.cpp
//发送广播
UECpp_Broadcast.Broadcast(FMath::RandRange(0, 100));
二、订阅及取消订阅
1、AUECpp_Receiver.h
protected:
virtual void BeginPlay() override;
public:
void OnReceived(int Param);
2、AUECpp_Receiver.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));
}