I am working on an automation plugin that generates and imports assets into levels. I am able to generate and load levels from my plugin’s c++ code and everything works correctly. However once the script has been run the LevelEditor module’s World attribute does not get set correctly and return NULL. This leads to some instability in the editor, which requires users to restart the editor after running the process to avoid a crash.
I am wondering what the correct process for unloading/loading worlds in the editor with C++ is so that LevelEditor’s world is correctly set.
My current world loading code looks like this:
bool FRNKImportCommandlet::LoadLevel(const FString& LevelToLoad)
{
bool bResult = false;
if (!LevelToLoad.IsEmpty())
{
UE_LOG(LogRNKImporterCommandlet, Log, TEXT("Loading Map %s"), *LevelToLoad);
FString Filename;
if (FPackageName::TryConvertLongPackageNameToFilename(LevelToLoad, Filename))
{
UPackage* Package = LoadPackage(NULL, *Filename, 0);
UWorld* World = UWorld::FindWorldInPackage(Package);
if (World)
{
// Clean up any previous world. The world should have already been saved
UWorld* ExistingWorld = GEditor->GetEditorWorldContext().World();
GEngine->DestroyWorldContext(ExistingWorld);
ExistingWorld->DestroyWorld(true, World);
GWorld = World;
World->WorldType = EWorldType::Editor;
FWorldContext& WorldContext = GEngine->CreateNewWorldContext(World->WorldType);
WorldContext.SetCurrentWorld(World);
// add the world to the root set so that the garbage collection to delete replaced actors doesn't garbage collect the whole world
World->AddToRoot();
GEngine->WorldAdded(World);
// initialize the levels in the world
if (!World->bIsWorldInitialized)
{
World->InitWorld(UWorld::InitializationValues().AllowAudioPlayback(false));
}
World->GetWorldSettings()->PostEditChange();
World->UpdateWorldComponents(true, false);
bResult = true;
}
}
}
else
{
// a map was not specified, ignore
bResult = true;
}
if (!bResult)
{
UE_LOG(LogRNKImporterCommandlet, Error, TEXT("Could not find or load level %s"), *LevelToLoad);
}
return bResult;
}
Any help would be greatly appreciated.