Unreal Engine 4 - Object & Actor Iterators

Unreal Engine 4 - Object & Actor Iterators

How to iterate over Actors and other UObjects in Unreal Engine 4.

Note: You should be careful using this regularly! You do not want to be iterating over every single object in your game every frame! This is useful for finding objects during a loading screen etc. when a manager/actor is first spawned, but is not appropriate to do on your Tick or timed event.

Actor Iterator

Unreal has an in-built Actor Iterator that will loop over all actors in a given world.

// Iterate over all actors, can also supply a different base class if needed
for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
	// Follow iterator object to my actual actor pointer
	AActor* MyActor = *ActorItr;
}

UObject Iterator

The UObject Iterator is a bit more interesting as it doesn't take a UWorld context. This means it will iterate over almost every UObject in memory. This can contain editor-only objects, objects from the editor-world when you're playing in-editor, objects from other multiplayer clients, and all sorts of interesting things!

However, most of the time, you will just want to find ones assigned to your game world. You can make sure you only use the ones in your actual game world by checking the world they belong to as you loop through.

const UWorld* MyWorld = GetWorld();
// change UObject to the type of UObject you're after
for (TObjectIterator<UObject> ObjectItr; ObjectItr; ++ObjectItr)
{
	// skip if this object is not associated with our current game world
    if (ObjectItr->GetWorld() != MyWorld)
    {
       continue;
    }
    
    UObject* Object = *ObjectItr;
    // ...
}