Skip to main content

08 - Interfaces

How to define a UINTERFACE and implement it on a class - the clean way to let many different actors share a contract.

Full source​

include "CoreMinimal.h"
include "GameFramework/Actor.h"

interface IExampleDamagable (api=EXAMPLES_API, minimal)
{
method public virtual void TakeDamage(float Amount) pure
}

uclass AExampleRobot : AActor implements IExampleDamagable meta: api=EXAMPLES_API
{
method public virtual void TakeDamage(float Amount) override {
UE_LOG(LogTemp, Warning, TEXT("robot took %f damage"), Amount);
}

method public virtual void BeginPlay() override {
Super::BeginPlay();
IExampleDamagable::Execute_TakeDamage(this, 25.0f);
}
}

Line by line​

  • interface IExampleDamagable (api=EXAMPLES_API, minimal) - declares the interface. minimal → MinimalAPI; api= sets the export macro.
  • method public virtual void TakeDamage(float Amount) pure - an interface method. pure makes it a pure virtual (= 0); implementers must supply the body.
  • uclass AExampleRobot : AActor implements IExampleDamagable - the class implements the interface.
  • method public virtual void TakeDamage(float Amount) override { ... } - the actual implementation.
  • IExampleDamagable::Execute_TakeDamage(this, 25.0f); - how you call an interface method on an arbitrary actor from C++ (via the generated Execute_ helper). In Blueprint you'd use the Interface Message node.

Key ideas​

  • Contract without inheritance - any actor (a crate, a door, a boss) can implement IExampleDamagable without sharing a base class.
  • Multiple interfaces - implements IFoo, IBar, … (comma-separated).
  • pure forces implementers to define the method.
  • Interfaces are a great fit for damageable, interactable, pickup, quest-giver style contracts.

From Blueprint​

  • Right-click an actor → Add Event → TakeDamage (if BlueprintImplementableEvent or implemented by the Blueprint).
  • Use the Interface Message node to call it polymorphically.

Next: 09 - AI Behavior.