Skip to content

strangechu's Blog

  • About me
  • GitHub
  • LinkedIn

strangechu's Blog

Work & Game

[UE4]從C++呼叫Blueprint實裝的interface函式

3 月 2, 2020 by strangechu

狀況

平常在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函式了!

參考資料

https://wiki.unrealengine.com/Interfaces_And_Blueprints

Post navigation

Previous Post:

[UE4]檢查Actor是否出現在畫面

Next Post:

[UE4] 處理DataTable的Import資料格式轉換

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

近期文章

  • 從《33遠征隊》看日本遊戲業的未來——JRPG的蛻變與停滯
  • 機戰傭兵6 玩後感
  • 沉沒意志 玩後感
  • Fallout影集觀後感
  • [CEDEC2024]薩爾達的餘料建造開發減法

近期留言

  • 「strangechu」於〈個人遊戲月報 2020年8月〉發佈留言
  • 「扇」於〈個人遊戲月報 2020年8月〉發佈留言

彙整

  • 2025 年 5 月
  • 2025 年 1 月
  • 2024 年 9 月
  • 2024 年 8 月
  • 2024 年 5 月
  • 2024 年 4 月
  • 2024 年 3 月
  • 2024 年 1 月
  • 2023 年 12 月
  • 2023 年 11 月
  • 2023 年 10 月
  • 2023 年 8 月
  • 2023 年 6 月
  • 2023 年 5 月
  • 2023 年 4 月
  • 2023 年 3 月
  • 2023 年 1 月
  • 2022 年 12 月
  • 2022 年 10 月
  • 2022 年 9 月
  • 2022 年 5 月
  • 2022 年 3 月
  • 2022 年 2 月
  • 2022 年 1 月
  • 2021 年 12 月
  • 2021 年 10 月
  • 2021 年 3 月
  • 2020 年 12 月
  • 2020 年 11 月
  • 2020 年 10 月
  • 2020 年 8 月
  • 2020 年 7 月
  • 2020 年 3 月
  • 2020 年 2 月
  • 2019 年 7 月
  • 2019 年 4 月

分類

  • Career
  • Game
  • Game Review
  • Monthly Report
  • UE4
  • UE5
  • Uncategorized
  • 技術
  • 演講心得

其他操作

  • 登入
  • 訂閱網站內容 RSS 資訊提供
  • 訂閱網站留言 RSS 資訊提供
  • WordPress 台灣繁體中文
© 2025 strangechu's Blog | WordPress Theme by Superbthemes