<style>.lazy{display:none}</style> Skip to main content

Unreal Engine C++ Fundamentals – Interfaces!

By May 30, 2019June 13th, 2019Development, Tutorial, Unreal

Hey guys,

Today we resume our C++ Fundamentals lessons by looking at interfaces and how they can help simply our life by allowing for common contracts to be shared by different game actors.

As usual you can find the start project on our GitHub page.

What is an interface ? Tell me !

An interface is an abstract definition of a contract. What this means is an interface defines how our class can be interfaced ( hah ! ) with while keeping the implementation details away.

More than that it allows us to create a common method signature between various disparate objects.

Consider I have an interface that has a method on it called “DoStuff” and I have two objects, Dog and Person, that inherit this interface. When I call Dog->DoStuff he may perform a trick while if I call the same method of Person->DoStuff he may tell me to fuck off and to stop bothering them. But from the point of view of the code interacting with those actors it’s the same behavior.

This allows for a lot of re-use and generic implementations while keeping the details of those implementations specific.

This all seems very abstract, show me code !

So let’s take a look at how an interface class is structured

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

/**
 * 
 */
class UE4FUNDAMENTALS09_API IInteractiveActor
{
  GENERATED_BODY()

  // Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
  void Interact();
};

As you can see it’s pretty thin in definition, we simply have a class that inherits from UInterface and then defines the method signature of “Interact”.

Excellent now we are cooking with fire, now what ?

Once we have the interface in place we now start including it on our objects. Let’s take a look at our InteractiveProp.

UCLASS()
class UE4FUNDAMENTALS09_API AInteractiveProp : public AActor, public IInteractiveActor
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  AInteractiveProp();

  UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Interact")
  class UStaticMeshComponent* BaseMesh;

protected:
  // Called when the game starts or when spawned
  virtual void BeginPlay() override;

public:	
  // Called every frame
  virtual void Tick(float DeltaTime) override;

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
  void Interact();	// prototype declaration
  virtual void Interact_Implementation() override;	// actual implementation of our interact method

private:
  bool bIsBig;
};

The major thing to note is that in order to leverage the interface, we modify our class signature to bring in “IInteractiveActor”

class UE4FUNDAMENTALS09_API AInteractiveProp : public AActor, public IInteractiveActor

Then we overwrite the Interact method by first declaring the prototype method signature and then the implementation one. Please note that the “_Implementation” is important and has to be exact for the reflection mechanic in Unreal to process your interface + implementation.

UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
void Interact();	// prototype declaration
virtual void Interact_Implementation() override;	// actual implementation of our interact method

So that was pretty straight forward, now how do I use these guys ?

To execute interface definitions we have a few ways of going about.

First we need to determine if an object uses an interface and we have two ways of checking that.

  1. Based on the ImplementsInterface check
  2. Using a cast to an interface object

Here is the first example

InteractHit.GetActor()->GetClass()->ImplementsInterface(UInteractiveActor::StaticClass())

And the second one

IInteractiveActor* InteractiveActor = Cast<IInteractiveActor>(InteractHit.GetActor());
if(InteractiveActor)
{
  // do stuff
}

Once you determine if an object has an interface the way you execute a call on that object is by passing it into the interface “Execute_” call.

IInteractiveActor::Execute_Interact(InteractHit.GetActor());

This basically says, for interface InteractiveActor Execute the method Interact and pass in our Actor on which that method will be triggered.

Here is a full code block that does this logic using a line trace fired from the player against an object.

void AUE4Fundamentals09Character::Interact()
{
  FVector Start;
  FVector End;

  FVector PlayerEyesLoc;
  FRotator PlayerEyesRot;

  GetActorEyesViewPoint(PlayerEyesLoc, PlayerEyesRot);

  Start = PlayerEyesLoc;
  End = PlayerEyesLoc + (PlayerEyesRot.Vector() * LineTraceDistance);

  FCollisionQueryParams TraceParams(FName(TEXT("InteractTrace")), true, this);

  FHitResult InteractHit = FHitResult(ForceInit);

  bool bIsHit = GetWorld()->LineTraceSingleByChannel(InteractHit, Start, End, ECC_GameTraceChannel3, TraceParams);

  if(bIsHit)
  {
    Log(ELogLevel::WARNING, InteractHit.Actor->GetName());
    // start to end, green, will lines always stay on, depth priority, thickness of line
    DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 5.f, ECC_WorldStatic, 1.f);

    // implements interface
    if(InteractHit.GetActor()->GetClass()->ImplementsInterface(UInteractiveActor::StaticClass()))
    {
      IInteractiveActor::Execute_Interact(InteractHit.GetActor());
    }
  }
}

That’s it folks !

In addition to the video here are a few resources for further reading:

 

3 Comments

  • andreas says:

    thanks for sharing,
    the gifs are top 🙂

  • kaludis says:

    Hey!
    First of all thanks for the helpful post and video.
    I just wondered is there any difference between UE UInterface stuff and native C++ virtual function?
    I mean we can implement the same functionality using last one:
    (Sorry for my imperfect English ;))

    // — Compiled code snippet —

    #include

    class Actor
    {
    public:
    virtual ~Actor() {}
    };

    class InteractiveActor
    {
    public:
    virtual ~InteractiveActor() {}

    // Calling private virtual function from non-virtual function
    void Interact() { Interact_Implementation(); };

    private:
    // Here we declare private virtual function of the i-face
    virtual void Interact_Implementation() = 0;
    };

    // InteractiveActor i-face powered actor
    class InteractiveProp : public Actor, public InteractiveActor
    {
    private:
    void Interact_Implementation() override { printf(“Wow!\n”); }
    };

    // Simple actor
    class NotInteractiveProp : public Actor
    {};

    void Filter(Actor* ptr)
    {
    InteractiveActor* iptr = dynamic_cast(ptr);

    if (iptr)
    {
    // We have successfully cast Actor-class-pointer-to-InteractiveProp-object to
    // implementation of InteractiveActor i-face in InteractiveProp object
    iptr->Interact();
    }
    else
    {
    // But in the case of Actor-class-pointer-to-NotInteractiveProp-object we have an iptr == nullptr
    // because NotInteractiveProp does not implement InteractiveActor i-face
    }
    }

    int main()
    {
    Actor* ptr1 = new InteractiveProp;
    Actor* ptr2 = new NotInteractiveProp;

    // This call prints ‘Wow!’
    Filter(ptr1);

    // But not this one
    Filter(ptr2);
    }

  • Dávid says:

    Hi! 5:05 in my actor file , when I included my Interface file and I wrote that public IMyInterface , I get this errors:
    error C2504: ‘IMyInterface’: base class undefined.
    C3668: ‘AMyActor::_getUObject’: method with override specifier ‘override’ did not override any base class methods
    What’s the problem?
    Thanks your answer!

Leave a Reply to andreas Cancel Reply