Unreal Crash when loadMap by CPP

Unreal Crash when loadMap by CPP

I am developing a feature to allow user to open a map from Editor Utilities Widget.
Here is my code:

bool UContentToolsEditorBlueprintLibrary::OpenMap()
{
	
	FString LevelPath = "/Game/Test/Maps/Demos/VTAR/Level_Instances/TestMap/TestMap.TestMap";
	
	if (ULevelEditorSubsystem* LevelEditorSubsystem = GEditor->GetEditorSubsystem<ULevelEditorSubsystem>())
	{
		if (FEditorModeTools* ModeManager = LevelEditorSubsystem->GetLevelEditorModeManager())
		{
			ModeManager->DeactivateAllModes();
		}
	}

	if (!GIsDemoMode)
	{
		// If there are any unsaved changes to the current level, see if the user wants to save those first.
		bool bPromptUserToSave = true;
		bool bSaveMapPackages = true;
		bool bSaveContentPackages = true;
		if (FEditorFileUtils::SaveDirtyPackages(bPromptUserToSave, bSaveMapPackages, bSaveContentPackages) == false)
		{
			return false;
		}
	}
	const bool bLoadAsTemplate = false;
	const bool bShowProgress = true;
	FEditorFileUtils::LoadMap(LevelPath, bLoadAsTemplate, bShowProgress);

	return true;
}```

If i exec the code with a simple level, it works well,
but when i exec the code with a special level (Have some sub levels), the unreal will crash, and it looks like the memory is leaking, here is the outlog before crash (Sooo sorry that i have to remove my company name):
![image|690x175](upload://ejxP4q597vBqT1oUjctBZ1istDb.png)

Can anyone help please!

Hi @ShouyuYang,

Welcome to the forums.

Have you tired using ULevelEditorSubsystem::OpenLevel to open your level instead?

Something like this:
if (ULevelEditorSubsystem* LevelEditorSubsystem = GEditor->GetEditorSubsystem<ULevelEditorSubsystem>())
{
LevelEditorSubsystem->LoadLevel(LevelPath);
}

I think OpenLevel is designed for opening levels in the editor.

Could you also try disable the DeactivateAllModes code and see if that is interfering in some way?

Another thing you could try is debug which sublevel is causing the issue.

Try this:
const TArray<ULevelStreaming*>& StreamingLevels = GWorld->GetStreamingLevels();

for (const ULevelStreaming* Level : StreamingLevels)
{
if (Level)
{
UE_LOG(LogTemp, Log, TEXT("Loading Sublevel: %s"), *Level->GetWorldAssetPackageName());
}
}

Hey! Thank you for help!

I dont find the OpenLevel function in the ULevelEditorSubsystem, but i did tested a lot of other functions which ‘should’ load the level, none of them works.

Sorry looks like it should have been LoadLevel but I’m guessing you tried that.

I’m not entirely sure what’s going on here. One thing you could try is creating a new level and adding each sublevel individually. This way, you can test to see which one is causing the issue.

None of the sub levels are causing a circular dependency?

Unfortunately, I wasn’t able to view the attached screenshot.