Unreal Engine C++: How to spawn a Blueprint by name

If you find yourself wanting to spawn a Blueprint class within C++, here’s how.

First, you need the project-specific path to your Blueprint. Here’s an easy way to get it:

  1. Open the UE editor.
  2. Find your Blueprint in the content browser.
  3. Right-click your Blueprint and click Copy Reference.

The path provided by Copy Reference will look something like this:

/Script/Engine.Blueprint'/Game/_Custom/Blueprints/Player/Pickups/Money/BP_MoneyPickup.BP_MoneyPickup'

You can delete everything up to and including the first apostrophe, and also the last apostrophe. You can then also delete the repeated Blueprint name (notice that it shows BP_BlueprintName.BP_BlueprintName). You should be left with something like this:

/Game/_Custom/Blueprints/Player/Pickups/Money/BP_MoneyPickup

This is the path that we’ll use in the code.

Next, use code similar to the following to get a class reference which you can then use with GetWorld()->SpawnActor or anywhere else that requires a class reference:

// Choose an appropriate value in place of AOLMoneyPickup. Use a class that
// that your Blueprint inherits from.
TSubclassOf<AOLMoneyPickup> MoneyPickupClass;
// Temporarily stores the class search result, and the class type which was
// found if the search succeeded. Note that this MUST be run only from within
// a constructor, otherwise it will fail.
auto MoneyPickupClassSearchResult = ConstructorHelpers::FClassFinder<AOLMoneyPickup>(TEXT("/Game/_Custom/Blueprints/Player/Pickups/Money/BP_MoneyPickup"));
if (MoneyPickupClassSearchResult.Succeeded())
{
    MoneyPickupClass = MoneyPickupClassSearchResult.Class;
}
else
{
    // Couldn't find the class. Log an error or something.
}

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.