How to safely store a pointer to my UINTERFACE?

Hi!

I have created an UINTERFACE called “MyInterface” i.e. UMyInterface and IMyInterface. A class that implements this interface and inheriting AActor. Then in the world I raycast where the mouse pointer is and get an actor back. I use InterfaceCast to cast it to “IMyInterface” which works good (I can e.g. call my methods). Now I want to store a pointer to my Interface in a way such that I can check something like IsValid because there is no guarantee this actor will live/exist during the whole playthrough.

How is the UE4 interface supposed to be used. If I store the “UMyInterface” I have access to a IsValid method, however then I have no longer access to my methods in “IMyInterface”. How are you supposed to go back and forth between the interfaces. Also how do you get the “UMyInterface” in the first place from e.g. an actor. I have hard to believe that you are supposed to cast the interfaces back and forth between each other instead of using a more type safe approach.

Thanks in advance!

You can store it in a TWeakObjectPtr<UYourInterface> MyInterfacePtr;
You can then use MyInterfacePtr.IsValid() to check whether the actor still exists.

If you want your class to take lifetime ownership of this interface, i.e. you do not want the garbage collector to destroy the actor while your class holds a pointer to it, then store it in an UPROPERTY() UMyInterface MyInterface;* in your class.

I can’t see my interface’s methods when I’m switching to using UUnit instead of IUnit?

My conclusion is that this isn’t possible to achieve in a typesafe way in unreal engine. Dynamic casts are required even though the types are known at compile time, or at least as long as UObjects and the garbage collector are involved.

so basically interfaces in unreal are pointless? I don’t get it…

Sadly, UInterfaces are almost useless, yes. There were some discussions on making them more useful, but it’s not a high priority thing at the moment.

I have an old feature request here also :slight_smile:

Interfaces are not useless but no type safety is supported. You will have to use dynamic casts when accessing interfaces in your application. For more detailed complaints I have regarding this you can read my feature request here