How to do it...

In a globally accessible object (such as your GameMode object), add a TSubclassOf< YourC++ClassName > UPROPERTY() to specify and supply the UCLASS name to your C++ code. To do this with the GameMode, do the following:

  1. From Visual Studio, open up the Chapter02_GameModeBase.h file from the Solution Explorer. From there, update the script to the following:
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "UserProfile.h"
#include "Chapter_02GameModeBase.generated.h"

/**
*
*/
UCLASS()
class CHAPTER_02_API AChapter_02GameModeBase : public AGameModeBase
{
GENERATED_BODY()

public:
UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = UClassNames )
TSubclassOf<UUserProfile> UPBlueprintClassName;
};
  1. Save and compile your code.
  2. From the UE4 editor, create a blueprint from this class. Double-click on it to enter the blueprints editor and then select your UClass name from the drop-down menu so that you can see what it does. Save and exit the editor:

  1. In your C++ code, find the section where you want to instantiate the UCLASS instance.
  2. Instantiate the object using ConstructObject< > with the following formula:
ObjectType* object = ConstructObject< ObjectType >( 
UClassReference );

For example, using the UserProfile object that we specified in the last recipe, we would get code such as this:

// Get the GameMode object, which has a reference to  
// the UClass name that we should instantiate: 
AChapter2GameMode *gm = Cast<AChapter2GameMode>( 
GetWorld()->GetAuthGameMode());
if( gm )
{
UUserProfile* newobject = NewObject<UUserProfile>(
(UObject*)GetTransientPackage(),
UUserProfile::StaticClass() );
}

You can see an example of this being used in the Chapter_02GameModeBase.cpp file in this book's example code.