BlueprintNativeEvent在ue4中是用来修饰UFUNCTION的,和BlueprintImplementableEvent有点类似,
BlueprintImplementableEvent用于实现C++调蓝图(声明在C++,实现在蓝图)
BlueprintNativeEvent除了实现C++调用蓝图外,同样会调用一个本地方法,本地方法为 声明的函数名+_Implementation
这样就可以实现一次调用,两个实现(c++实现,蓝图实现)
BlueprintNativeEvent还有一个比较有用的用法,是C++实现可以是virual,具体用法如下:
//.h file
UFUNCTION(BlueprintNativeEvent)
void Foo();
virtual void Foo_Implementation();
//.cpp
void ACustomActor::Foo_Implementation()
{
// needed functionality
}
//Thus, you'll be able to override it like this:
virtual void Foo_Implementation() override;
//Also please don't forget to define the function in .cpp file of the derived class:
void ADerivedActor::Foo_Implementation()
{
// needed functionality
}
引擎中很多地方就是用这种用法来实现派生类重写BlueprintNativeEvent函数的C++实现
写本文的目的,不光是为了记录BlueprintNativeEvent的用法,更是因为本人今天遇到的一个奇怪bug
按照前文的用法,我的函数实现如下:
// .h
UFUNCTION(BlueprintNativeEvent, Category = Health)
void TestFunc();
virtual void TestFunc_Implementation();
// .cpp
void AMyCharacter::TestFunc_Implementation()
{
}
但是很不幸,编译报错如下:
error C2535: “void AMyCharacter::TestFunc_Implementation(void)”: 已经定义或声明成员函数
把virtual void TestFunc_Implementation();代码注释了就好了,而且派生类中的TestFunc_Implementation方法也能正常调用。
后来发现是因为AMyCharacter声明的时候用的是GENERATED_UCLASS_BODY宏
而引擎中的代码用BlueprintNativeEvent时,用的是GENERATED_BODY宏
也就是说,当使用GENERATED_UCLASS_BODY宏时,基类声明无需加virtual void TestFunc_Implementation()
而使用GENERATED_BODY时,基类声明需要加virtual void TestFunc_Implementation()
ps : 以上使用ue4版本为4.21测试,其他版本用法可能会有不同