I want to make an interface that calls some functions whenever a derived class created.

I want to design an interface in Unreal Engine. It is important for me to have immediate access to the functions implemented by this interface. What I want is for every class that implements this interface to automatically register itself into a list. For now, I’m handling this using Register/Remove functions. However, someone might forget to call Register/Remove, which can lead to unexpected behavior or crashes. Because of this, I want to automate these Register/Remove functions. How can I do that?

  • I tried using TObjectIterator, but I don’t want to iterate over all objects.

  • My interface can be inherited in Blueprint as well, so that also needs to be considered.

UINTERFACE(Blueprintable)
class UTestInterface : public UInterface
{
    GENERATED_BODY()
};

class SomeClassForStatics
{
public:
    static TArray<TScriptInterface<UTestInterface>> ObjectList;
};

class ITestInterface
{
    GENERATED_BODY()
public:
    void RegisterObject(const TScriptInterface<UTestInterface>& Interface) const
    {
       SomeClassForStatics::ObjectList.Add(Interface);
    }
    void RemoveObject(const TScriptInterface<UTestInterface>& Interface) const
    {
       SomeClassForStatics::ObjectList.Remove(Interface);
    }
};

you could bind to a world delegate like FWorldDelegates::OnActorSpawned and check if it implements interface?

1 Like

Thanks for the answer. The interface won’t be used only by Actors — other UObjects in the system will also use it. I could control the Actors through a delegate as you suggested, but UObjects make up almost half of the classes implementing this interface. Therefore, I don’t think that approach will be sufficient.