狀況
平常在C++使用Interface功能時習慣用Cast來轉換使用。然而在UE4想製作在Blueprint實裝的Interface功能時,卻發現在C++不能正常Cast。以下說明此狀況的對應方法。
說明
在C++實裝的Interface,我們可以用Cast來進行轉換使用:
IMyInterface MyInterface = Cast<IMyInterface>(ActorInstance); if (MyInterface) { // Other code }
然而,如果該Actor的Interface實裝方法不是在C++,而是在Blueprint定義的話,Cast將會失敗,由於C++層中該Actor並沒有實裝該Interface。在這裡要使用ImplementsInterface:
if (ActorInstance->GetClass()-> ImplementsInterface(UMyInterface::StaticClass())) { // Other code }
如此我們成功判斷了該Actor是否實裝了該Interface。但是我們依然不能Cast!那該如何呼叫Interface的函式呢?假設我們的IMyInterface.h定義如下:
#include "UObject/Interface.h" #include "IMyInterface.generated.h" UINTERFACE() class THIRDPERSON_API UMyInterface : public UInterface { GENERATED_BODY() }; class THIRDPERSON_API IMyInterface { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, BlueprintNativeEvent) void DoSomething(); };
DoSomething() 為我們想呼叫的函式。由於我們希望實裝在Blueprint,所以宣告為BlueprintNativeEvent。如果在C++要呼叫此函式,必須使用Static版本的函式,呼叫例子如下:
if (ActorInstance->GetClass()-> ImplementsInterface(UMyInterface::StaticClass())) { IMyInterface::Execute_MyInterfaceFunction(ActorInstance); }
如此就能成功呼叫在Blueprint實裝的Interface函式了!