Unreal Engine C++ interfaces that also work in Blueprints
This info seems to be scattered across a ton of different docs pages and blog posts so I’m consolidating it here for my own sanity.
This example is an Interactable
interface, something a player can “interact” with. I don’t know if you should actually include Interface
in the name of your interface but I did here.
Create interface
You can do this with the usual class generator but note the following!
Important: Note the UINTERFACE(BlueprintType)
and the second _Implementation
function definition, as well as the U
and I
prefixes.
UINTERFACE(BlueprintType)
class UInteractableInterface : public UInterface
{
GENERATED_BODY()
};
class FLAB_API IInteractableInterface
{
GENERATED_BODY()
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
bool Interact(AFlabCharacter* Interactor);
virtual bool Interact_Implementation(AFlabCharacter* Interactor);
};
Implement interface in C++
Put the I
version of your interface in your class definition and make it a BlueprintType
:
UCLASS(BlueprintType)
class ALootItem : public AActor, public IInteractableInterface
Override both methods in your h file:
public:
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Loot")
bool Interact(bool ExampleArg);
virtual bool Interact_Implementation(bool ExampleArg) override;
Implement only the _Implementation
method in your cpp file:
bool ALootItem::Interact_Implementation(bool ExampleArg)
{
return !ExampleArg;
}
Test for & use interface functions in C++
Don’t call Interact
or Execute_Interact
directly, and don’t use ImplementsInterface
because it doesn’t seem to work
AActor* Target = GetSomeActor();
// The Target could be some interactable object, like an ALootItem
if (Target->Implements<UInteractableInterface>())
{
// Now we can safely use our interface function
bool ExampleArg = false;
bool Result = IInteractableInterface::Execute_Interact(Target, ExampleArg);
}
Use in Blueprints
Open the “Class Settings” in your Blueprint:
Under the “Interfaces” category add your interface:
The overridable methods will then be listed next to your Blueprint functions under “Interfaces”: