【转载】BlueprintImplementableEvent 与 BlueprintNativeEvent

2,221 阅读2分钟

原文链接

我对原文的一些错误进行了修正,并对格式进行了调整,并补充了一些细节,方便未来查阅

定义辨析

/// 这个函数被设计为被蓝图覆盖。 C++ 不要为这个函数提供主体;  
/// 自动生成的代码将包含一个调用 ProcessEvent 来执行覆盖体的转换。
BlueprintImplementableEvent

/// 这个函数被设计为被蓝图覆盖,但也有一个本地实现。  
/// 提供一个名为 [函数名]_Implementation 的函数体,而不是直接 [函数名]; 
/// 自动生成的代码将包含一个自动转换,在必要时调用实现方法。
 BlueprintNativeEvent
  • BlueprintImplementableEvent:在 C++ 可以 声明 函数(但不能定义,蓝图重写),在 C++ 里 调用 该函数,蓝图重写实现该函数 【没有自由

  • BlueprintNativeEvent:在 C++ 可以 声明定义 函数,在 C++ 里 调用 该函数,蓝图可以 重写 实现该函数(蓝图可以重写或不重写 C++ 父类函数)【有自由

具体实例

MyTPCharacter.h 中的函数声明

BlueprintImplementableEventBlueprintNativeEvent 两者都可以在 C++ 中声明

UFUNCTION(BlueprintImplementableEvent)
void TestA();

UFUNCTION(BlueprintImplementableEvent)
int TestB();

UFUNCTION(BlueprintImplementableEvent)
void TestC(const FString &str);

UFUNCTION(BlueprintImplementableEvent)
int TestD(const FString &str);

UFUNCTION(BlueprintNativeEvent)
void TestE();

UFUNCTION(BlueprintNativeEvent)
int TestF();

UFUNCTION(BlueprintNativeEvent)
void TestG(const FString &str);

UFUNCTION(BlueprintNativeEvent)
int TestH(const FString &str);

MyTPCharacter.cpp 的函数定义

BlueprintImplementableEvent 由于不能在 C++ 中定义,所以 cpp 中仅有 BlueprintNativeEvent 的定义。

BlueprintNativeEvent 修饰函数定义格式:函数名 _Implementation

void AMyTPCharacter::TestE_Implementation()
{
    PrintScreenStr("TestE_Implementation");
}
int AMyTPCharacter::TestF_Implementation()
{
    PrintScreenStr("TestF_Implementation");
    return 1;
}
void AMyTPCharacter::TestG_Implementation(const FString &str)
{
    PrintScreenStr("TestG_Implementation " + str);
}
int AMyTPCharacter::TestH_Implementation(const FString &str)
{
    PrintScreenStr("TestH_Implementation " + str);
    return 1;
}

C++ 如何调用

不用加 _Implementation

void AMyTPCharacter::OnRunEvent()
{

    TestA();
    TestB();
    TestC("TestC");
    TestD("TestC");
    TestE();
    TestF();
    TestG("TestG");
    TestH("TestH");
}

蓝图可以重写以上所有函数:如下图,选中重写实现

image.png

以上定义的各函数有返回值和没有返回值在蓝图中的区别,如下

image.png

TestETestF 是由 BlueprintNativeEvent 修饰的函数(分别无返回值有返回值),在蓝图中,它可以重写 C++ 父类函数,如下

image.png

image.png

运行效果:

image.png

总结

  1. 如果没有函数返回值,那就是类似蓝图事件通知,
  2. 如果有函数返回值,那就是类似蓝图函数重写(覆盖)
  3. 都可以传参和返回值;
  4. BlueprintNativeEvent 修饰函数在 C++ 有声明和定义实现,在蓝图可以覆写该函数,蓝图中可以选择是否调用 C++ 定义父类函数;

例如:

//.h
UFUNCTION(BlueprintNativeEvent)
void OnOverlap(AActor* OverlappedActor, AActor* OtherActor);

//.cpp
// 绑定
OnActorBeginOverlap.AddDynamic(this, &ABaseCoin::OnOverlap);
...
void ABaseCoin::OnOverlap_Implementation(AActor* OverlappedActor, AActor* OtherActor) {
	if (Cast<ABasePlayer>(OtherActor) != nullptr)
	{
		Destroy();
	}
}

  1. BlueprintImplementableEvent 修饰函数只有声明,没有定义实现,只能在蓝图重写实现;BlueprintNativeEventBlueprintImplementableEvent 修饰的函数都只能在 C++ 其他【非它俩修饰的】函数里调用。

例如:

由蓝图实现。

UFUNCTION(BlueprintImplementableEvent)
void Jump();

image.png

相关文章

【转载】BlueprintCallable 与 BlueprintPure

【转载】Blueprintable\NotBlueprintType 与 EditAnywhere\EditDefaultsOnly\EditInstanceOnly