---
# System prepended metadata

title: Interface
tags: [Unreal Engine]

---

# Interface
Interfaces are a powerful feature that allow we to **define a set of functions that can be implemented by multiple classes**, regardless of their position in the inheritance hierarchy. This enables a form of polymorphism, where different classes can be treated uniformly if they implement the same interface. Interfaces are especially useful for defining common behaviors across disparate classes.
## Create C++ Interface
Step 1: Generate the Interface Files
- Open Unreal Editor
- Files -> New C++ Class
- Select **None** as parent class.

Step 2: Modify the Generated Files
- Example:
```cpp=
#pragma once

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

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

/**
 * Interface class. Implement this class to add custom functionality.
 */
class MYPROJECT_API IMyInterface
{
    GENERATED_BODY()

public:
    // Add interface functions to this class.
    virtual void MyInterfaceFunction() = 0;
```

## Implement the Interface in a Class
- Modify a class to implement interface:
```cpp=
#include "MyInterface.h" // Include the interface header

UCLASS()
class MYPROJECT_API AMyActor : public AActor, public IMyInterface
{
    GENERATED_BODY()

public:
    AMyActor();

protected:
    virtual void BeginPlay() override;

public:
    virtual void Tick(float DeltaTime) override;

    // Implement the interface function
    virtual void MyInterfaceFunction() override;
};
```

## Use the Interface
- Example:
```cpp=
// Find all actors that implement the interface
TArray<AActor*> FoundActors;
UGameplayStatics::GetAllActorsWithInterface(GetWorld(), UMyInterface::StaticClass(), FoundActors);

// Call the interface function on each actor
for (AActor* Actor : FoundActors)
{
    IMyInterface* Interface = Cast<IMyInterface>(Actor);
    if (Interface)
    {
       Interface->MyInterfaceFunction();
    }
}
```

## Implement the Interface in Blueprint
If we want to make the interface implemented in Blueprint, we have add the macros:
- BluprintNativeEvent 
    - C++: Default implementation.
    - Blueprint: Can override the default C++ implementation. 
```cpp=
// In MyInterface.h
UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
void MyInterfaceFunction();
```
```cpp=
// In MyActor.h
virtual void MyInterfaceFunction_Implementation() override;
```
- BlueprintImplementableEvent
    - C++: No implementation.
    - Blueprint: Must be implemented in Blueprints. 

```cpp=
UFUNCTION(BlueprintCallable, BlueprintImplementableEvent)
void MyInterfaceFunction();
```
## Use the Interface which Implemented in Blueprint
- Example:
```cpp=
// Check if it is implemented in Blueprint
if (UKismetSystemLibrary::DoesImplementInterface(Actor, UMyInterface::StaticClass()))
{
    IMyInterface::Execute_MyInterfaceFunction(Actor, Param1, Param2 ...);
}
```