Of course! Creating C++ interfaces in Unreal Engine is a powerful way to decouple your code and define common "contracts" that different Actors or Objects can fulfill. For example, you could have an IInteractable interface that doors, chests, and NPCs can all implement, each with their own unique Interact() behavior.
Because C++ doesn't have a native interface keyword like C# or Java, Unreal uses a special system with macros and two class declarations. Let's walk through it step-by-step.
The Core Concept: UInterface and IInterface
For every interface you create (e.g., Interactable), you'll actually define two classes in the same header file:
UInteractableInterface: Inherits from UInterface. This is the part that the Unreal reflection system (UObject system) understands. It's used for casting, checking implementations in Blueprints, and other engine-level features. You almost never interact with it directly in C++.
IInteractableInterface: Inherits from IInterface. This is the actual C++ interface that your classes will inherit from. It's where you declare the functions that implementing classes must define.
Step 1: Create the Interface Header File
First, create a new C++ class in the Unreal Editor. In the "Add C++ Class" wizard, choose "Unreal Interface" from the list of common classes. This is the easiest way as it will set up the file structure for you.
Let's name it InteractableInterface. This will create a file named InteractableInterface.h.
If you create the file manually, here is the complete code you would put in InteractableInterface.h.
cpp
// InteractableInterface.h
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "InteractableInterface.generated.h"
// This class does not need to be modified.
UINTERFACE(MinimalAPI, Blueprintable) // Blueprintable makes it usable in Blueprints
class UInteractableInterface : public UInterface
{
GENERATED_BODY()
};
/**
* The actual C++ interface class that our other classes will inherit from.
*/
class YOURPROJECT_API IInteractableInterface
{
GENERATED_BODY()
// Add interface functions to this class. They are virtual by default.
public:
/**
* A C++ and Blueprint implementable function.
* The implementing class must define Interact_Implementation.
* Can be called from both C++ and Blueprints.
*/
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Interaction")
void Interact(APawn* InstigatorPawn);
/**
* A Blueprint-only implementable function.
* There is NO C++ implementation for this. It must be implemented in a Blueprint.
* Can be called from C++, but will only do something if implemented in a child Blueprint.
*/
UFUNCTION(BlueprintImplementableEvent, BlueprintCallable, Category = "Interaction")
void OnLookedAt(APawn* InstigatorPawn);
/**
* A pure C++ interface function. No UFUNCTION macro.
* Cannot be called or overridden in Blueprints.
* Implementing classes just override this function normally.
*/
virtual FString GetInteractText() const = 0;
};
Key UFUNCTION Specifiers:
BlueprintNativeEvent: The most flexible and common type. It allows for a default C++ implementation but can also be overridden in Blueprints. Unreal will generate a function signature for you to implement called FunctionName_Implementation().
BlueprintImplementableEvent: For functions you only want to implement in Blueprints. You do not provide a C++ implementation for these.
BlueprintCallable: Allows this function to be called from Blueprint graphs.
Step 2: Implement the Interface on an Actor
Now, let's create an Actor that can be interacted with, like a door.
MyDoorActor.h
In the header file for your actor, you need to:
Include the interface header: #include "InteractableInterface.h"
Add IInteractableInterface to the list of parent classes.
Declare the override for the interface functions.
cpp
// MyDoorActor.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "InteractableInterface.h" // 1. Include the interface
#include "MyDoorActor.generated.h"
UCLASS()
class YOURPROJECT_API AMyDoorActor : public AActor, public IInteractableInterface // 2. Add to inheritance
{
GENERATED_BODY()
public:
AMyDoorActor();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
// 3. Declare the override for the interface functions
// For BlueprintNativeEvent, we override the _Implementation function
virtual void Interact_Implementation(APawn* InstigatorPawn) override;
// We don't declare OnLookedAt here because it's BlueprintImplementableEvent
// For the pure C++ function, we override it normally
virtual FString GetInteractText() const override;
private:
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* DoorMesh;
bool bIsOpen = false;
};
MyDoorActor.cpp
In the source file, provide the implementations for your functions.
cpp
// MyDoorActor.cpp
#include "MyDoorActor.h"
// ... constructor and other functions ...
// Note the _Implementation suffix! This is required for BlueprintNativeEvent.
void AMyDoorActor::Interact_Implementation(APawn* InstigatorPawn)
{
// This is our default C++ behavior
bIsOpen = !bIsOpen;
if (bIsOpen)
{
UE_LOG(LogTemp, Warning, TEXT("Door is now OPEN!"));
// Add logic to rotate the door mesh, play a sound, etc.
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Door is now CLOSED!"));
}
}
// Standard virtual function override for the pure C++ function
FString AMyDoorActor::GetInteractText() const
{
return bIsOpen ? FString(TEXT("Press E to Close")) : FString(TEXT("Press E to Open"));
}
Step 3: Using the Interface (Calling the Functions)
Now, let's make a player character that can find and use these interactable objects. The key is to check if an object implements the interface before trying to call its functions.
Here is an example from a Player Character class that performs a line trace to find an object to interact with.
cpp
// MyPlayerCharacter.cpp
void AMyPlayerCharacter::TryInteract()
{
FVector Start = GetFollowCamera()->GetComponentLocation();
FVector End = Start + (GetFollowCamera()->GetForwardVector() * 500.f); // 500 units trace
FHitResult HitResult;
FCollisionQueryParams Params;
Params.AddIgnoredActor(this); // Ignore self
GetWorld()->LineTraceSingleByChannel(HitResult, Start, End, ECC_Visibility, Params);
if (HitResult.bBlockingHit)
{
AActor* HitActor = HitResult.GetActor();
if (HitActor)
{
// --- THIS IS THE KEY PART ---
// Check if the actor we hit implements our interface.
// Method 1: The standard Cast<>
IInteractableInterface* Interface = Cast<IInteractableInterface>(HitActor);
if (Interface)
{
// Call the pure C++ function directly
FString InteractText = Interface->GetInteractText();
UE_LOG(LogTemp, Log, TEXT("Hovering over: %s"), *InteractText);
// To call a UFUNCTION (especially one that might be implemented
// in Blueprint), you MUST use the Execute_ prefix.
// This calls the special "thunk" function generated by Unreal.
Interface->Execute_Interact(HitActor, this);
}
// Method 2: A direct check (less common, but useful to know)
if (HitActor->GetClass()->ImplementsInterface(UInteractableInterface::StaticClass()))
{
// You still need to call with Execute_
IInteractableInterface::Execute_Interact(HitActor, this);
}
}
}
}
Important: The Execute_ Prefix
When you call an interface function that is a UFUNCTION (like our Interact and OnLookedAt), you must use the Execute_ prefix.
Incorrect:Interface->Interact(InstigatorPawn); // This will fail to compile or link.
The Execute_ function is a static "thunk" generated by the Unreal Header Tool. It correctly figures out whether to call the C++ _Implementation or the overridden function in Blueprint.
For pure C++ virtual functions (like our GetInteractText), you call them directly without any prefix.
Summary
Create: Use the Editor's "Add C++ Class" wizard and select Unreal Interface.
Define: Add functions to the IYourInterface class declaration in the .h file. Use BlueprintNativeEvent for maximum flexibility.
Implement: Add IYourInterface to your Actor's inheritance list and override the interface functions. Remember to use the _Implementation suffix in the .cpp file for BlueprintNativeEvents.
Use: Use Cast<IYourInterface>(MyActor) to safely get a pointer to the interface.
Call: Call UFUNCTION interface methods using the Execute_FunctionName() syntax. Call pure C++ methods directly.