How to save any UObject to a package

Dec, 2 2021— #basic

You can save any object that is presented as an asset (UPackage) with this:

bool SaveToAsset(UObject* ObjectToSave)
{
	UPackage* Package = ObjectToSave->GetOutermost();
	const FString& PackageName = Package->GetName();
	const FString& PackageFileName = FPackageName::LongPackageNameToFilename(PackageName, FPackageName::GetAssetPackageExtension());
	const bool bSuccess = UPackage::SavePackage(Package, nullptr, RF_Public | RF_Standalone, *PackageFileName, GError, nullptr, false, true, SAVE_NoError);

	if (!bSuccess)
	{
		UE_LOG(LogTemp, Error, TEXT("Package '%s' wasn't saved!"), *PackageName)
		return false;
	}

	UE_LOG(LogTemp, Warning, TEXT("Package '%s' was successfully saved"), *PackageName)
	return true;
}
By Georgy Treshchev

Unreal Engine Developer. Contact for any questions. Telegram chat, e-mail, Github.