What does this topic explains?
Actually I am studying unreal engine with “Ue4 Scripting with c++ cookbook” by PACKT publication.
And I can’t understand what this topic is trying to explain…
See the topic under this heading “Casting to a UInterface implemented in native code”
Casting to a UInterface implemented in native code
One advantage that UInterfaces provide you with as a developer is the ability to treat a collection of heterogeneous objects that implement a common interface as acollection of the same object, using Cast< > to handle the conversion.
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 reuse a project and GameMode from a previous recipe.
How to do it…
Open your game mode’s declaration and add a new property to the class:
UCLASS() class CHAPTER_07_API AChapter_07GameModeBase : public AGameModeBase { GENERATED_BODY() public:
virtual void BeginPlay() override;
TArray<IMyInterface*> MyInterfaceInstances;
};
Add #include “MyInterface.h” to the header’s include section:
#pragma once #include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "MyInterface.h"
#include "Chapter_07GameModeBase.generated.h"
Add the following within the game mode’s BeginPlay implementation:
for (TActorIterator<AActor> It(GetWorld(), AActor::StaticClass()); It; ++It)
{
AActor* Actor = *It;
IMyInterface* MyInterfaceInstance = Cast<IMyInterface>(Actor);
// If the pointer is valid, add it to the list
if (MyInterfaceInstance)
{
MyInterfaceInstances.Add(MyInterfaceInstance);
}
}
// Print out how many objects implement the interface
FString Message = FString::Printf(TEXT("%d actors implement the interface"), MyInterfaceInstances.Num());
GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, Message);
Since we are using the TActorIterator class, we will need to add the following #include to the top of our GameModeBase class’ implementation file:
#include "EngineUtils.h"
// TActorIterator If you haven’t done so already, set the level’s game mode override to your5.
game mode, then drag a few instances of your custom Interfaceimplementing actor into the level.
When you play your level, a message should be printed on screen that.
indicates the number of instances of the interface that have been implemented in Actors in the level: