Level streaming with C++

I’ve done an insane amount of testing with loading levels. Streaming levels (or any level) is never completely loaded when the call returns even if you set it to be blocking. It takes MANY ticks for it to complete. But with Level Streaming, you have an advantage. You can give it a delegate to let you know when it’s done. And actually done.

Here is sample code that I’m currently using. It uses level instances, but streaming levels are the same.

bool Success = false;
ULevelStreamingDynamic* DynamicLevel = ULevelStreamingDynamic::LoadLevelInstanceBySoftObjectPtr(world, this->PreviewLevelInstance, PlatformPosition, rot, Success);
check(Success);
this->LastLevelInstance = DynamicLevel;
FScriptDelegate D;
D.BindUFunction(this, FName("PostLoadLevel"));
DynamicLevel->OnLevelShown.Add(D);

There is an OnLevelUnloaded event as well. So you can chain your events. You could unload your level in PostLoadLevel and then use the OnLevelUnloaded with PostUnloadLevel function or something like that.

For main levels, you need to override the GameInstance’s OnWorldChanged method and then set a delegate on the level’s OnBeginPlay event by using World->GetOnBeginPlayEvent().

For streaming levels, something like this maybe…

  ULevelStreaming *StreamingLevel = UGameplayStatics::GetStreamingLevel(this, FName("SubLevel1"));
  FScriptDelegate D;
  D.BindUFunction(this, FName("PostLoadLevel"));
  StreamingLevel->OnLevelLoaded.Add(D);
  UGameplayStatics::LoadStreamLevel(world, FName("SubLevel1"), true, false, FLatentActionInfo());