How to get BP with FClassFinder?

How to get BP through FClassFinder? When using this code, I get an error (screenshot), despite the fact that literally everything works in another C++ class. I tried both AActor and AWeapon.

void AMyCharacter::BeginPlay()
{
	Super::BeginPlay();
	FVector Location = this->GetActorLocation();
	FRotator Rotation = this->GetActorRotation();
	FActorSpawnParameters SpawnInfo;
	ConstructorHelpers::FClassFinder<AActor> BP_Weapon_M4(TEXT("/Game/MyGameFolder/Weapon/BP_Weapon"));
}

This is another class and here it’s working

AMyHUD::AMyHUD() : Super() 
{
	ConstructorHelpers::FClassFinder<UUserWidget> WB_Crosshair(TEXT("/Game/MyGameFolder/HUD/WB_Crosshair"));

	MainHUD = WB_Crosshair.Class;
}

I tried to copy this code to MyCharacter class and it’s not working. I don’t understand why.

Hi there, the issue you’re encountering with FClassFinder in your AMyCharacter class but not in your AMyHUD class is likely due to the fact that FClassFinder is intended to be used in constructors and not in functions like BeginPlay.

Why FClassFinder Works in Constructor but Not in BeginPlay

FClassFinder uses ConstructorHelpers::FClassFinder, which is designed to be used only in constructors. The CheckIfIsInConstructor function enforces this by ensuring that FClassFinder is used only during object construction. This is why your AMyHUD class’s constructor works fine but your AMyCharacter::BeginPlay method does not.

Solution: Use StaticLoadObject or StaticLoadClass for Runtime Loading

To load a class at runtime (e.g., in BeginPlay), you should use StaticLoadObject or StaticLoadClass instead of FClassFinder.

You could try something along these lines…

void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();

    FVector Location = this->GetActorLocation();
    FRotator Rotation = this->GetActorRotation();
    FActorSpawnParameters SpawnInfo;

    // Use StaticLoadClass to load the class at runtime
    UClass* BP_Weapon_M4_Class = StaticLoadClass(AActor::StaticClass(), nullptr, TEXT("/Game/MyGameFolder/Weapon/BP_Weapon.BP_Weapon_C"));
    if (BP_Weapon_M4_Class)
    {
        // You can now use BP_Weapon_M4_Class to spawn your weapon or other logic
        AActor* SpawnedWeapon = GetWorld()->SpawnActor<AActor>(BP_Weapon_M4_Class, Location, Rotation, SpawnInfo);
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("Failed to load BP_Weapon_M4 class"));
    }
}

Hope this helps.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.