How to call interface method from c++?

I have an interface GetInteractionComponent. It’s written on C++. I implemented this interface intro my character into blueprint.

I do next code:

UE_LOG(LogClass, Log, TEXT("This a testing statement. %s"), *Owner->GetName());
IGetInteractionComponent *interface = Cast<IGetInteractionComponent>(Owner);

if(interface != nullptr){
            UE_LOG(LogTemp, Warning, TEXT("Tick C"));
}

In logs I recieve my character’s names, but I don’t recieve “Tick C” message. It means that interface cast is null. What I am doing wrong?

If you implement interface on a Blueprint, cast to IInterface will always return nullptr. You should use the following method:

if(Owner->GetClass()->ImplementsInterface(UGetInteractionComponent::StaticClass())
{
    UE_LOG(LogTemp, Warning, TEXT("Tick C"));
    IGetInteractionComponent::Execute_NameOfFunctionToExecute(Owner);  // To call interface function
} 

And how can I input params of the function? Can you give me an example?

Also how can I check, if interface is implemented into actor using cpp?

To call a function with params:

IGetInteractionComponent::Execute_NameOfFunctionToExecute(Owner /*Object which implement interface */, Param1, Param2)

“ImplementsInterface” method will always work, whether the interface has been implemented in c++ or Blueprints.
There are also two more ways to check whether an object implements a c++ or Blueprint interface:

// 1
if(Owner->Implements<UGetInteractionComponent>())
{
}
// 2
if(UKismetSystemLibrary::DoesImplementInterface(Owner, UGetInteractionComponent::StaticClass())
{
}

For c++ only interfaces you can use Cast method. It’s a bit faster.

1 Like