Proper way of loading a BluePrint from GameMode C++

You must pass the class of your doorBP class to the SpawnActor function.

Here is the code:



void ATestProjectGameMode::BeginPlay()
 {
     UWorld * const World = GetWorld();
     if (World)
     {
         // Your doorBP is an Actor so
         World->SpawnActor<AActor>(doorBPClass);
     }
 }


So you need to find doorBPClass. There are several approaches for this to work.

  1. Hold it as TSubclassOf property in your GameMode and load with the help of ConstructorHelpers::FObjectFinder; just like you did to find the DefaultPawnClass.


class ATestProjectGameMode : public AGameMode
 {
     GENERATED_BODY()
 
 public:

     UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "X") TSubclassOf<AActor> doorBPClass;
 };




ATestProjectGameMode::ATestProjectGameMode()
 {
     // use our custom PlayerController class
     PlayerControllerClass = ATestProjectPlayerController::StaticClass();
 
     // set default pawn class to our Blueprinted character
     static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/TopDownCPP/Blueprints/TopDownCharacter"));
     if (PlayerPawnBPClass.Class != NULL)
     {
         DefaultPawnClass = PlayerPawnBPClass.Class;
     }

     static ConstructorHelpers::FClassFinder<AActor> doorBPClassFinder(TEXT("/Game/TopDownCPP/Blueprints/doorBP"));
     if (doorBPClassFinder.Class != nullptr)
     {
         doorBPClass = doorBPClassFinder.Class;
     }
 }


Note: If your doorBp’s parent class was not Actor (for example ACharacter). Then you need this:



// header
TSubclassOf<ACharacter> doorBPClass;
// and
SpawnActor<ACharacter>(doorBPClass);


  1. You can hold your variables, references, classes, assets in Singleton object instead of your GameMode. Look for Rama’s tutorial. This is the most easy way I’ve found.
    A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums
1 Like