Create new asset from code (save UObject to asset)

How can I save some existing UObject to .uasset file from code? I want to do: Instantiate an object of UMyClass, fill it with data and then save it as .uasset.

Is something like this or similar possible?

Thank You for any help.

PS. The reason I want to do this is that i want to be able to create files in editor (from code) and make sure those files are then included in packaged game. Currently, the only files being packaged are .uassets (without modifying settings, but that’s something I don’t want to do since it’s a plugin)

1 Like

Yes. You need to make sure that you construct your object with RF_StandAlone. Then you can save it using SavePackage(). There are plenty of examples inside the editor on how to do this.

1 Like

Thank You, I have somehow figured this already - although I wouldn’t be so sure about “plenty” :stuck_out_tongue:

UTestingAsset is a UDataAsset.

#include "AssetRegistryModule.h"

void ATCharacter::TestAssetSave( )
	FString AssetPath = FString("../../../Playground/Content/Dev/");
	FString PackagePath = FString("/Game/Dev/TestingAsset");

	UPackage *Package = CreatePackage(nullptr, *PackagePath);
	UTestingAsset* TestAsset = NewObject<UTestingAsset>(Package, UTestingAsset::StaticClass(), *FString("TestingAsset"), EObjectFlags::RF_Public | EObjectFlags::RF_Standalone);

	TestAsset->TestFloat = 3.14;
	TestAsset->TestInt = 12;
	TestAsset->TestString = FString("Testing this string");


	FString FilePath = FString::Printf(TEXT("%s%s%s"), *AssetPath, *FString("TestingAsset"), *FPackageName::GetAssetPackageExtension());
	bool bSuccess = UPackage::SavePackage(Package, TestAsset, EObjectFlags::RF_Public | EObjectFlags::RF_Standalone, *FilePath);

	UE_LOG(LogTemp, Warning, TEXT("Saved Package: %s"), bSuccess ? TEXT("True") : TEXT("False"));	

1 Like

I had to also reload the package generated this way (either by restarting the editor, or by calling ReloadPackage in PackageReload.h) in order to be able to edit the asset, as otherwise the editor would have complained about it being only partially loaded.