UInterfaces are a pair of classes that work together to enable classes to exhibit polymorphic behavior among multiple class hierarchies. This recipe shows you the basic steps involved in creating a UInterface
purely in code.
.h
file to start, and name it MyInterface.h.
MyInterface.cpp
as your implementation file.#include "MyInterface.generated.h" /** */ UINTERFACE() class UE4COOKBOOK_API UMyInterface: public UInterface { GENERATED_BODY() }; /** */ class UE4COOKBOOK_API IMyInterface { GENERATED_BODY() public: virtualFStringGetTestName(); };
.cpp
file:#include "UE4Cookbook.h" #include "MyInterface.h" FString IMyInterface::GetTestName() { unimplemented(); return FString(); }
UObject
, which uses UCLASS
, we need to use the UINTERFACE
macro to declare our new UInterface
.UE4COOKBOOK_API
to help with the exporting of library symbols.UObject
portion of the interface is UInterface
.UCLASS
types, we require a macro to be placed inside the body of our class so that the auto-generated code is inserted into it.GENERATED_BODY()
for UInterfaces. The macro must be placed at the very start of the class body.UE4COOKBOOK_API
, and is named in a specific way.UInterface
-derived class and the standard class have the same name but a different prefix. The UInterface
-derived class has the prefix U
, and the standard class has the prefix I
.GENERATED_BODY()
macro. IInterface
.UInterface
, as it is declared by the Unreal Header Tool, and requires an implementation.GetTestName()
function. Without this, the linking phase of compilation will fail. This default implementation uses the unimplemented()
macro, which will issue a debug assert when the line of code is executed.18.118.119.229