Programatically created asset fails to save, or crashes the editor.

I’m writing a portion that generates a base material from C++, creates and connects certain nodes. I can open the generated material asset after running the code and everything works great. But in UE 5.0 when I try to save that asset it gives an error: “Asset failed to save as it was partially loaded”. And in UE 5.1 the editor crashes as soon as I try to open the generated asset.

Here is how I create the asset:

// Create and setup package
	FString MaterialBaseName = MaterialName;
	FString PackageName = "/Game/ShaderUtil/ShaderGen/";
	PackageName += MaterialBaseName;
	UPackage* Package = CreatePackage(nullptr, *PackageName);

	// Create and setup generated material asset 
	UMaterialFactoryNew* MaterialFactory = NewObject<UMaterialFactoryNew>();
	UObject* RawMaterial = MaterialFactory->FactoryCreateNew(UMaterial::StaticClass(), Package,
		*MaterialBaseName, RF_Standalone | RF_Public,
		nullptr, GWarn);
	// NOTE: Var name is macro specific, exercise caution when changing it.
	UMaterial* _GenMaterial = Cast<UMaterial>(RawMaterial);
	FAssetRegistryModule::AssetCreated(_GenMaterial);
	Package->FullyLoad();
	Package->SetDirtyFlag(true);

After this I add the nodes and other logic that goes into the material, then:

// Final change notifies and state sets
	_GenMaterial->MaterialDomain = EMaterialDomain::MD_UI;
	_GenMaterial->PreEditChange(nullptr);
	_GenMaterial->PostEditChange();

After hours of debugging I can’t seem to find the issue. Any help would be greatly appreciated.

Hi Vahan_Davtian,

I do it in a very similar way and it works ok - I do the material changes and PreEditChange and PostEditChange before the AssetCreated and FullLoad lines though (and I do the AssetCreated last). I do a check-out and save between them too:

UPackage* Package = CreatePackage(nullptr, *PackageName);
...
_GenMaterial->PreEditChange(nullptr);
_GenMaterial->PostEditChange();
...
Package->FullyLoad();
Package->SetDirtyFlag(true);
FEditorFileUtils::PromptForCheckoutAndSave({Package},false,false);
...
FAssetRegistryModule::AssetCreated(_GenMaterial);