[C++] Load a class reference to a blueprint at runtime?

I have a variable of type TSubclassOf named “spawnedClass”. The intention is to find a particular blueprint in the project via text filepath and assign its class to spawnedClass. This must be done at runtime, as the desired blueprint may change at any time.

How would I do so via C++?

Here is the answer I came up with. Please add another answer if you’ve found a better way.

TSubclassOf<AActor> spawnedClass;

// This string is obtained by right clicking the asset in the content browser and selecting "CopyReference", then pasting in a text file.
FString spawnedBlueprintReference = TEXT("Blueprint'/Game/FirstPersonCPP/Blueprints/FirstPersonProjectile.FirstPersonProjectile'");
    
UObject* loadedObject = StaticLoadObject(UObject::StaticClass(), nullptr, *spawnedBlueprintReference);
    
UBlueprint* castedBlueprint = Cast<UBlueprint>(someObject);
    
if (castedBlueprint && castedBlueprint->GeneratedClass->IsChildOf(AActor::StaticClass()))
{
    // Don't forget the asterisk
    spawnedClass = *castedBlueprint->GeneratedClass;
}
2 Likes