Object/Actor Iterators(对象/Actor迭代器)
对象迭代器是非常实用的工具,用于在特定 UObject 类型和子类的所有实例上进行迭代
// Will find ALL current UObjects instances for (TObjectIterator<UObject> It; It; ++It) { UObject* CurrentObject = *It; UE_LOG(LogTemp, Log, TEXT("Found UObject named: %s"), *CurrentObject.GetName()); }
为迭代器提供更为明确的类型即可限制搜索范围。假设您有一个派生自 UObject,名为 UMyClass 的类。您会发现此类的所有实例(以及派生自此类的实例)与此相似:
for (TObjectIterator<UMyClass> It; It; ++It) { // ... }
Actor 迭代器与对象迭代器的工作方式非常相近,但只能用于派生自 AActor 的对象。Actor 迭代器不存在下列问题,只返回当前游戏世界实例使用的对象。
创建 actor 迭代器时,需要为其赋予一个指向 UWorld 实例的指针。许多 UObject 类(如APlayerController)会提供 GetWorld 方法,助您一臂之力。如不确定,可在 UObject 上检查 ImplementsGetWorld 方法,确认其是否应用 GetWorld 方法。
APlayerController* MyPC = GetMyPlayerControllerFromSomewhere(); UWorld* World = MyPC->GetWorld(); // Like object iterators, you can provide a specific class to get only objects that are // or derive from that class for (TActorIterator<AEnemy> It(World); It; ++It) { // ... }