How to load a blueprint class and spawn it in C++?

From what I understand, gaining direct access to a BP from C++ is not very easy or practical. I’m still relatively new to using C++ but here is what I’ve done thus far to help me, so maybe the logic can be applied to your needs or get your wheels spinning anyway.

I’ve needed to gain access to Widget BP and Component BP’s from my C++ classes. So what I did for example, with my Widget was I create a C++ child class of a UserWidget called PrimaryWidget and on my Player Character, I have the following

PlayerCharacter.h

// Property that assigns the BP object
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly)
TSubclassOf<UUserWidget> HUD;

// Holds the reference to our Inventory Widget Screen that we use to reference the BP
// UPrimaryWidget is the name of my base widget class where HUD widget is derived from
UPROPERTY(VisibleInstanceOnly)
class UPrimaryWidget* HUDWidgetReference;

PlayerCharacter.cpp

void APlayerCharacter::BeginPlay()
{
check(HUD)

HUDWidgetReference = Cast<UPrimaryWidget>(CreateWidget(PlayerControllerRef, HUD));

Just make sure to then go into the player character assign the BP to the HUD property inside of blueprints, without it the check(HUD) will throw an exception. I then have access to the blueprint from my Player Character. This isn’t an exact fix, you still can’t access properties and methods you create inside the blueprint. In this case, it is best to have a C++ parent class that has the default properties and methods assigned to it, then the methods and properties implemented inside the blueprint. This will allow you access to those properties and methods then.

I’m sure this exact example won’t help you in your exact situation but perhaps it can get your gears grinding to find the right example for you. You want to try and eliminate as many hard reference calls to files (AssetFile(TEXT("/Game/BP_StatueActor.BP_StatueActor"))) as much as possible. Move a file and the game crashes.

Good luck, hope I was even slightly helpful!

1 Like