UInterface in Unreal Engine C++



Index

  1. What are Interfaces?
  2. Simple Interface Example
  3. Check if Interface exists on object
  4. Invoke Interface function on object
  5. Default Implementation for specific class

What are Interfaces?

Interfaces are classes which have functions within them that other classes can inherit and implement/override in their own version, It is used to avoid casting.

Note: Interface classes CANNOT have UPROPERTY() variables


Simple Interface Example

// ExampleInterface.h

#pragma once

#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "ExampleInterface.generated.h"

UINTERFACE(MinimalAPI)
class UExampleInterface : public UInterface
{
    GENERATED_BODY()
};


class MYPROJECT_API IExampleInterface
{
    GENERATED_BODY()

    public:
       
       UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
       void MyExample();

       UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
       void MyArgExample(bool MyArg);  // With Arguments (Default arguments are not supported)
};
// ExampleCharacter.h

#include "ExampleInterface.h"

...

UCLASS()
class MYPROJECT_API AExampleCharacter : public ACharacter, public IExampleInterface
{
    GENERATED_BODY()

    ...

    public:    
    virtual void MyExample_Implementation() override;
    virtual void MyArgExample_Implementation(bool MyArg) override;
};
// ExampleCharacter.cpp

void AExampleCharacter::MyExample_Implementation(){
   ...
}
void AExampleCharacter::MyArgExample_Implementation(bool MyArg){
   ...
}

Check if Interface exists on object

AExampleCharacter* ExampleCharacterObject;
bool DoesImplement = ExampleCharacterObject->Implements<UExampleInterface>(); // Use the "U-" prefix class

Invoke Interface function on object

AActor* ExampleCharacterObject;

if(ExampleCharacterObject->Implements<UExampleInterface>()){
  IExampleInterface::Execute_MyExample(ExampleCharacterObject); // Execute_*
  IExampleInterface::Execute_MyArgExample(ExampleCharacterObject, true /* , add, other, arguments*/); // Execute_*
}

Default Implementation for specific class

In this example the "specific class" is AActor

// ExampleInterface.cpp

...

UExampleInterface::MyExample_Implementation(){
    AActor * DerivedObject = Cast<AActor>(this);
}

Warning: This is more of a hack / proof of concept, Not recommended