C++和蓝图混用事件

一、在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宏

三、在蓝图中订阅、取消订阅动态多播委托

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值