1. 程式人生 > 實用技巧 >基於C++程式碼的UE4學習(十五)—— 將實現了介面類的ACTOR類進行型別轉換

基於C++程式碼的UE4學習(十五)—— 將實現了介面類的ACTOR類進行型別轉換

將實現了介面類的ACTOR類進行型別轉換,將其轉換為介面類。

沿用之前的(十三、十四)工程。

在GAMEBASE的標頭檔案裡新增如下程式碼:

1 TArray<IMyInterface*>actorlist;

在GAMEBASE原始檔裡的程式碼:

 1 // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
 2 
 3 
 4 #include "MyProject7_INTERFACEGameModeBase.h"
 5 #include "MyActor.h"
 6 #include "MyProject7_INTERFACE/MyInterface.h
" 7 #include "Engine.h" 8 9 10 void AMyProject7_INTERFACEGameModeBase::BeginPlay() { 11 Super::BeginPlay(); 12 13 FTransform spawnLocation; 14 //FTransform trans = FTransform(FRotator(0), FVector(0), FVector(0)); 15 for (int i = 0; i < 10; i++) { 16 AMyActor* spawnActor = GetWorld()->SpawnActor<AMyActor>(AMyActor::StaticClass(), spawnLocation);
17 18 UClass* actorClass = spawnActor->GetClass(); 19 20 if (actorClass->ImplementsInterface(UMyInterface::StaticClass())) { 21 GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, TEXT("Implements the Interface")); 22 } 23 } 24 25 for (TActorIterator<AActor>it(GetWorld(), AActor::StaticClass()); it; ++it) { //用到了ACOTR的迭代器,it指標傳入兩個引數,意思是在世界關卡中找Actor類的物件,++it不能寫成it++。
26 IMyInterface* myinterface = Cast<IMyInterface>(*it);//將實現了介面類的ACTOR物件進行型別轉換。 27 28 if (myinterface) { 29 actorlist.Add(myinterface); //將型別轉換成功的IMyInterface類的物件放入陣列。 30 } 31 }
32 33 FString result = FString::Printf(TEXT("the numbers of the interface was Implemented %d"),actorlist.Num()); 34 35 GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Blue, result); 36 37 }

效果如下: