Loading Blueprint From C++

Build.CS:

PublicDependencyModuleNames.AddRange(
	new string[] {
		"Core",
		"Json",
		"Engine",
		"CoreUObject",

		"AssetRegistry"
	}
);

Somewhere.H

#include "AssetRegistryModule.h"

Somewhere.CPP

void MyBase::LoadStuff()
{
	TArray<FAssetData>AssetData;

	const FAssetRegistryModule & AssetRegistry =
	FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry");

	AssetRegistry.Get().GetAssetsByClass( TEXT("MyBaseClass_NAME") , AssetData );



	// check if valid:
	for (const auto & Data : AssetData)
	{
		if (Data.AssetName.ToString().Equals( TEXT("MySubClassIneed") , ESearchCase::CaseSensitive) )
		{
			UBlueprint* BP = GetBlueprintFromCDO(Data.GetAsset());
			if (BP && BP->GeneratedClass.Get())
			{
				if(
					!BP->GeneratedClass.Get()->HasAnyClassFlags(CLASS_Deprecated|CLASS_Hidden)
				) {
					// UMyBaseType* CDO = GetCDOfromBlueprint<UMyBaseType>(BP);
					// I do stuff in CDO.. 'GetCDOxx' above doesn't exist in your copy of Unreal.
				}
				break;
			}
		}
	}
}


Now, what I actually do, but it’s optional… I create a custom UBlueprint class and a custom asset factory to create blueprints from this class:

UCLASS(BlueprintType)
class MYPROJECT_API UMyCoreSystemBlueprint : public UBlueprint
{
	GENERATED_UCLASS_BODY()

#if WITH_EDITOR

	virtual bool SupportedByDefaultBlueprintFactory() const override
	{
		return false;
	}

#endif
};

I will not get into details of how to create asset factory, I talk about asset factory here.


So, back to topic, with a custom BP class I make sure I load Blueprints I need without hardcoding name of classes into C++ files (hardcoded text and names is a bad practice):

AssetRegistry.Get().GetAssetsByClass
(
	UMyCoreSystemBlueprint::StaticClass()->GetFName() , AssetData, true
);
1 Like