keywords: UE4, iterate, iterator, TObjectIterator, TActorIterator, run-time

原文:Object Iterators

遍历所有SkeletalMeshComponent

for ( TObjectIterator<USkeletalMeshComponent> Itr; Itr; ++Itr )
{
    // Access the subclass instance with the * or -> operators.
    USkeletalMeshCompoment *Component = *Itr;
    ClientMessage(Itr->GetName());
}

遍历所有Texture

for(TObjectIterator<UTexture2D> Iter; Iter; ++Iter)
{
    if(UTexture2D* Tex = *Iter)
    {
        Tex->LODBias = LODBias;
        Tex->UpdateResource();
    }
}

遍历所有StaticMeshActor

for (TActorIterator<AStaticMeshActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
    // Same as with the Object Iterator, access the subclass instance with the * or -> operators.
    AStaticMeshActor *Mesh = *ActorItr;
    ClientMessage(ActorItr->GetName());
    ClientMessage(ActorItr->GetActorLocation().ToString());
}

遍历所有Character

for (TActorIterator<ACharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
    if (ActorItr->GetName().Contains("beiminghuoque"))
    {
        AMyCharacter* Warrior = (AMyCharacter*)*ActorItr;
        FString msg = FString::Printf(TEXT("#########:%d"), (int)Warrior->State());
        GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, msg);
    }
}

遍历所有自定义Character:

for (TActorIterator<AMyCharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{    
}
注意事项

如果用不带GetWorld()的方式遍历,比如这种方式:

for (TObjectIterator<AMyCharacter> Itr; Itr; ++Itr)

则当编辑器中打开蓝图后(双击蓝图),该蓝图也会出被遍历出来。不打开则不在遍历范围内。

诡异效果:

即使是打包版本,TObjectIterator也会遍历已加载的pak中的对象,即使这些对象不在当前场景中。

这两种不会,它们只会遍历当前场景内的运行时对象:

for (FConstPawnIterator Itr = GetWorld()->GetPawnIterator(); Itr; ++Itr)

for (TActorIterator<AMyCharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr)

如何遍历当前场景内运行时的所有灯光:

for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
    AActor* Actor = *ActorItr;
    TArray<UActorComponent*> PrimitiveComps; 
    Actor->GetComponents(UActorComponent::StaticClass(), PrimitiveComps);
    for (UActorComponent* Comp : PrimitiveComps)
    {
        if (ULocalLightComponent* Light = Cast<ULocalLightComponent>(Comp))
        {
            if (Light->Mobility == EComponentMobility::Movable)
            {
            }
        }
    }
}