1. 程式人生 > >UE4 C++ 建立一個介面

UE4 C++ 建立一個介面

介面的建立不需要通過編輯器,可以直接使用IDE將介面的.h和.cpp建立到專案目錄下的Source資料夾下的工程名資料夾裡。Source->專案名資料夾。

這裡建立一個簡單的空的介面MyInterface
MyInterface.h

#pragma once

#include "MyInterface.generated.h"

UINTERFACE()
class MyProjectName_API UMyInterface : public UInterface
{
	GENERATED_BODY()
};

class MyProjectName_API IMyInterface
{
	GENERATED_BODY()
	public:
	UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Interactable)
		bool CanInteract();
	virtual bool CanInteract_Implementation();
	
	UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Interactable)
		void PerformInteract();
	virtual void PerformInteract_Implementation();
};

UMyInterface並不是我們需要的介面,IMyInterface才是,UMyInterface的存在是因為Unreal Engine 4的反射系統的需要。

the UINTERFACE class is not the actual interface; it is an empty class that exists only for visibility to Unreal Engine’s reflection system. The actual interface that will be inherited by other classes must have the same class name, but with the initial “U” changed to an “I”.

https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Reference/Interfaces#determiningifagivenclassimplementsyourinterface

標記為BlueprintNativeEvent的函式,既可以在C++中被覆蓋,也可以在藍圖中覆蓋,如果C++中也覆蓋了,藍圖中也覆蓋了,以藍圖的為主。
_Implementation()為對應函式的預設實現。

MyInterface.cpp

#include "MyInterface.h"
bool IMyInterface::CanInteract_Implementation()
{
	return true;
}

void IMyInterface::PerformInteract_Implementation()
{

}