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.
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"));
}
}