Casting to a UInterface implemented in native code

One advantage that UInterfaces provides you with as a developer is the ability to treat a collection of heterogeneous objects that implement a common interface as a collection of the same object, using Cast< > to handle the conversion.

Note

Please note that this won't work if your class implements the interface through a Blueprint.

Getting ready

You should have a UInterface, and an Actor implementing the interface ready for this recipe.

Create a new game mode using the wizard within Unreal, or optionally, reuse a project and GameMode from a previous recipe.

How to do it...

  1. Open your game mode's declaration, and add a new UPROPERTY() macro to it:
    UPROPERTY()
    TArray<IMyInterface*>MyInterfaceInstances;

Get Unreal Engine 4 Scripting with C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.