How to import assets automatically through code and what is UPackage?

Answered by myself for people after, I am still not clear what a UPackage is but I fixed my code to work.
The second string parameter refers to the destination path must starts with “/Game/”. “/Game/” refers to the path to Contents folder so the code will work by changing it to:

		FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools");
		AssetToolsModule.Get().ImportAssets(TEXT("C:/MyProject/Content/Raw/dog.fbx"), TEXT("/Game/Imported/Dog"));

There will be a prompt to set import arguments, so I changed it to UAssetToolsImpl::ImportAssetsAutomated.

		TArray<FString> filesToImport;
		FString srcPath = TEXT("C:/MyProject/Content/Raw/dog.fbx");
		srcPath = srcPath.Replace(TEXT("\\"), TEXT("/"));
		filesToImport.Add(srcPath);

		UAutomatedAssetImportData* importData = NewObject<UAutomatedAssetImportData>();
		importData->bReplaceExisting = true;
		importData->DestinationPath = TEXT("C:/MyProject/Content/Imported/Dog");
		importData->Filenames = filesToImport;

		FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools");
		auto importedAssets = AssetToolsModule.Get().ImportAssetsAutomated(importData);

You can also add other files like texture and normal map to the importData’s Filenames array to import them together.

By the way, this function must be called within GameThread, if you are doing it in a sub thread you can tries to deal it with methods in this post:

Hope this helps someone.

2 Likes