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
// 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){
...
}
AExampleCharacter* ExampleCharacterObject;
bool DoesImplement = ExampleCharacterObject->Implements<UExampleInterface>(); // Use the "U-" prefix class
AActor* ExampleCharacterObject;
if(ExampleCharacterObject->Implements<UExampleInterface>()){
IExampleInterface::Execute_MyExample(ExampleCharacterObject); // Execute_*
IExampleInterface::Execute_MyArgExample(ExampleCharacterObject, true /* , add, other, arguments*/); // Execute_*
}
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