How To: Create New Assets in C++

Aug 31, 2021.Knowledge
When writing editor scripts or plugins, it may be useful to be able to programmatically create a new asset that appears in the content browser. There are a few helper functions available to help with this, here’s an example that creates the asset and updates the asset registry, as well as pointing the content browser to display the new asset:
// Load necessary modules
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked(“AssetTools”);
FContentBrowserModule& ContentBrowserModule = FModuleManager::LoadModuleChecked(“ContentBrowser”);
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked(TEXT(“AssetRegistry”));
IAssetRegistry& AssetRegistry = AssetRegistryModule.Get();

// Generate a unique asset name
FString Name, PackageName;
AssetToolsModule.Get().CreateUniqueAssetName(TEXT("/Game/AssetFolder/AssetName"), TEXT(""), PackageName, Name);
const FString PackagePath = FPackageName::GetLongPackagePath(PackageName);

// Create object and package
UPackage* package = CreatePackage(PackageName);
MyFactory = NewObject(UBlueprintFactory::StaticClass()); // Can omit, and a default factory will be used
UObject* NewObject = AssetToolsModule.Get().CreateAsset(Name, PackagePath, UBlueprint::StaticClass(), MyFactory);
UPackage::Save(package, NewObject, RF_Public | RF_Standalone, *FPackageName::LongPackageNameToFilename(PackageName, FPackageName::GetAssetPackageExtension()));

// Inform asset registry

// Tell content browser to show the newly created asset
TArray<UObject*> Objects;

Note that for your object class, you will need to use an object that is eligible to be displayed in the content browser as an asset. For example, when creating an actor asset, the UBlueprintFactory should be used instead of the UActorFactory (to create a UBlueprint asset describing the creation of an actor).