How to access a specific actor in GameMode class

For example, I manually added an AmbientSound actor to the level under current UWorld. I would like to search through all actors in this level and get a hold of the AmbientSound actor.

I want to try the following but not sure what to do.

  1. In the GameMode constructor, I tried to use GetWorld() but get a null pointer.
  2. if I could use GetWorld(), then I may iterate through GetWorld()->ActiveGroupActors to find out ambientsound.

This doesn’t directly address your requirement since you wanted it in the constructor, but I had difficulty with some objects in the constructor and moved it to BeginPlay. This worked when in BeginPlay and perhaps what you are using will work as well:

    for (TActorIterator<AActor> ActorItr(GetWorld()); ActorItr; ++ActorItr )
    {
        if(GEngine) {
           GEngine->AddOnScreenDebugMessage(-1, 15.f, FColor::Green,ActorItr->GetName());
           GEngine->AddOnScreenDebugMessage(-1, 15.f, FColor::Green,ActorItr->GetActorLocation().ToString());
           //etc...
        }
    }

Looping through with the iterator was something I found in one of Rama’s tutorials.

Yep, in UE4 the constructor should only be used for the most fundamental initialization of your object, which doesn’t rely on any external objects existing. Generally BeginPlay is the place to do the kind of thing you’re trying.

In this particular case, if you need the initialization to be done before anything else, you can override AGameMode::InitGame instead. This will get called before any actor’s BeginPlay, but the UWorld and its placed actors will exist.