Calling on Interface Crash??

Hi all, so I want to loop through all of my actors and check if they implement my interface. I’ve done that correctly with no issues but when I call the execute function, my program crashes. Does anyone know why this is happening?
Here’s my code:
for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
if (ActorItr->GetClass()->ImplementsInterface(UMainInterface::StaticClass()))
{
IMainInterface::Execute_OnPlayerDeath(ActorItr->GetClass());
//print(“Done”);
}
}
Any help is much appreciated, thank you :slight_smile:

The argument to Execute_OnPlayerDeath should be the actor, not the class.

Or you could use:



for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
    if (IMainInterface* Interface = Cast<IMainInterface>(ActorItr))
    {
        Interface->OnPlayerDeath();
    }
}

Thanks for the help but when I try this I get this error:
error C2665: ‘Cast’: none of the 3 overloads could convert all the argument types
while trying to match the argument list ‘(TActorIterator<AActor>)’

Yes I thought so as well but when I just put in the argument ActorItr, I get a red underline and an error that says,
No suitable conversion function from TActorIterator<AActor> to UObject* exists

You can’t use Cast() unless it’s purely a CPP-implemented interface with only Blueprint-Callable functions. If you implement the interface in a Blueprint class, the cast will fail anyway.

Even if the interface is implemented in CPP, any BlueprintNativeEvents will crash if you try to call them this way.


For OP - You’re currently trying to execute the function on the class object, which is why you are getting the crash. If the compiler complains it’s because you’re missing a required include.



IMainInterface::Execute_OnPlayerDeath(ActorItr->GetClass());


Should be:



IMainInterface::Execute_OnPlayerDeath(ActorItr);


I might have done something wrong but I have tried this and I’ve got an error
No suitable conversion function from TActorIterator<AActor> to UObject* exists
I put IMainInterface::Execute_OnPlayerDeath(ActorItr);

You need to get the actual actor pointer from the iterator like so:



Actor* TheActor = ActorItr.Get();

or

Actor* TheActor = *ActorItr;


Thank you so much it’s now working :slight_smile: