Casting blueprint actors that implement c++ interfaces

Hi guys,
I’ve got a game system where I need to be able to execute functions on both c++ and blueprint actors that implement a c++ interface (IBaseGameObject). When i try to cast the blueprint actor i get null, however if I use the cast while calling the function it actually works.

IBaseGameObjectType* test = Cast<IBaseGameObjectType>(SpawnedActor); //test results in null here if SpawnedActor is a blueprint calls that implements the IBaseGameObject c++ interface

Cast<IBaseGameObjectType>(SpawnedActor)->Execute_OnGameObjectActivate(SpawnedActor); //This however executes ok.

I’m getting around this currently by using the below code to check if the interface is implemented (rather than just testing the result of the Cast())
bool ImplementsInterface = SpawnedActor->GetClass()->ImplementsInterface(UBaseGameObjectType::StaticClass());

Just wondering if maybe there’s something I should be doing when casting blueprint actors that implement a c++ interface?


You pretty much have to check for both object version and native version of the Interface;
The target Blueprint might have one or the other implemented, so if the native Cast() fails then your check using ImplementsInterface() is correct since that will look for the object version of the Interface (which can be attached to Blueprints on Editor).

In case anyone runs into this problem, I was having a similar problem and here is how I fixed it:

Problem: In C++, casting a blueprint-defined actor or actor component to an interface would fail and return nullptr.

Solution: Create a C++ parent class for the blueprint-defined actor or component which implements the interface. The parent class simply has to implement the interface but all the logic inside the interface functions can still be placed in the child blueprint. After I did this I was able to cast just fine.


Yeah you can’t cast if the interface was implemented in Blueprint - If you want to check for a BP-implemented interface, you need to use the following (this works for both CPP and BP-implemented interfaces)

if (Object->Implements<UMyInterface>())
    IMyInterface::Execute_MyFunction(Object, Params...);

The only time it’s safe to cast and call the functions directly, is if:

  1. The interface is natively implemented.
  2. The interface does not have any BlueprintEvent functions (BlueprintCallable, BlueprintPure only are fine).

Personally I try to stay away from implementing interfaces in BP because it’s just a bit gross - but sometimes it can’t be avoided I guess.


Excellent Explanation