zer0から始めるプログラミング生活

unreal EngineやUnityのTipsを書いていきます。

【Unreal C++】⑥Interface【UE4】

今回はC++とブループリントでインターフェースを呼ぶ機会があったので備忘録として。
他にもいい方法があると思うのであくまで参考程度でお願いします。
エンジンはVer4.18.3を使用しています。
ちなみにブループリントインターフェースなどインターフェースについては以下のリンクを参照してください。
docs.unrealengine.com
unrealengine.hatenablog.com


①クラスの作成&宣言

おそらくBP側で作成したインターフェースはC++側に呼ぶことが出来ないのでC++側でインターフェースを作成します。C++でインターフェースを継承したクラスを作成します。
関数指定子をBlueprintImplementableEventでもいけるという情報もありましたが、参考したサイトの多くがBlueprintNativeEventを使用していたのでこちらを使用します。
unreallife.hatenablog.com


hogeInterface.h

#include "CoreMinimal.h"
#include "hogeInterface.generated.h"

UINTERFACE(Blueprintable)
class hogeProject_API UhogeInterface : public UInterface
{
	GENERATED_UINTERFACE_BODY()
};


class hogeProject_API IhogeInterface
{
	GENERATED_IINTERFACE_BODY()

public:
	UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
		void hogeFunc();
}

hogeInterface.cpp

#include "hogeInterface.h"


UhogeInterface::UhogeInterface(const FObjectInitializer& ObjectInitializer)
	:Super(ObjectInitializer)
{
}

void IhogeInterface::hogeFunc_Implementation()
{
}

ブループリントでの実装

イベント側

「Event hogeFunc」を呼んであげます。

イベントを呼び出すためには「Class Settings→interface→Implemented Interface」に先ほど作成したhogeInterfaceを追加してコンパイルする必要があります。

呼び出し側

「hogeFunc(Message)」を呼んであげます。
Targetノードにはイテレータ、Get All Actors with Interface、Get All Widgets with Interfaceなどを用いて検索したイベント側のクラスを繋いであげます。
自分はレベルストリーミング使用しているのでGet All Widgets of Classの第2引数のTop Level Onlyはfalseにしました。

f:id:bigden:20180214202143p:plain

C++での実装

イベント側(hogeActor)

hogeInterface を継承したクラスを作成し、関数をOverrideしてあげます。

hogeActor.h

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "hogeInterface.h”
#include "hogeActor.generated.h"

UCLASS()
class hogeProject_API AApple : public AActor, public IhogeInterface
{
	GENERATED_BODY()
public:
	//Interface 
	virtual void hogeFunc_Implementation() override;
};

hogeActor.cpp

void hogeActor::hogeFunc_Implementation()
{
//処理
}

呼び出し側

検索して配列に格納してRanged-forを用いて配列に対して処理をしてあげます。

TArray<AhogeActor*>hogeActAry;
UWorld* World=GEngine->GameViewport->GetWorld();
UGameplayStatics::GetAllActorsWithInterface(World,UhogeInterface::StaticClass(),hogeActAry);
for(AhogeActor* hogeAct : hogeActAry)
{
IhogeInterface::Execute_hogeFunc(hogeAct);
}


Get All Actors of Class、Get All Widgets of Classなどは遅い処理なのでTickなどで呼ばないでください。
docs.unrealengine.com