一、在C++中创建动态多播委托
1、UEBpAndCpp_Sender.h
//声明一个蓝图可调用的多播委托的类型
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FUEBpAndCpp_Broadcast, int, Param);
//创建对象
UPROPERTY(BlueprintAssignable)
FUEBpAndCpp_Broadcast UEBpAndCpp_Broadcast;
注意:相比纯C++多播委托,宏名字多了DYNAMIC单词
2、UEBpAndCpp_Sender.cpp
//广播
UEBpAndCpp_Broadcast.Broadcast(FMath::RandRange(0, 100));
二、在C++中订阅、取消订阅动态多播委托
1、UEBpAndCpp_Receiver_G.h
#include "UEBpAndCpp_Receiver_Parent.h"
protected:
virtual void BeginPlay() override;
public:
UFUNCTION()
void OnReceived(int Param);
注意:一定要加UFUNCTION
2、UEBpAndCpp_Receiver_G.cpp
#include "UEBpAndCpp_Receiver_G.h"
#include "UEBpAndCpp_Sender.h"
#include "Engine/Engine.h"
#include "Kismet/GameplayStatics.h"
void AUEBpAndCpp_Receiver_G::BeginPlay()
{
Super::BeginPlay();
//订阅动态多播委托
AUEBpAndCpp_Sender* PlayerPawn = Cast<AUEBpAndCpp_Sender>(UGameplayStatics::GetPlayerPawn(this, 0));
PlayerPawn->UEBpAndCpp_Broadcast.AddDynamic(this, &AUEBpAndCpp_Receiver_G::OnReceived);
//取消订阅动态多播委托
PlayerPawn->UEBpAndCpp_Broadcast.RemoveDynamic(this, &AUEBpAndCpp_Receiver_G::OnReceived);
}
void AUEBpAndCpp_Receiver_G::OnReceived(int Param)
{
GEngine->AddOnScreenDebugMessage(INDEX_NONE, 10.0f, FColor::Green, FString::Printf(TEXT("%i"), Param));
}
注意:这里相比纯C++多播委托,由AddUObject函数变为了AddDynamic宏
三、在蓝图中订阅、取消订阅动态多播委托