How to spawn a Blueprint from C++?

Hello,

I know that there have been a few similar questions, but all doesn’t work for me. It’s extremely frustrating to spawn something in UE4. My code:

in h.

TSubclassOf<class AActor> BHGrenade;

in cpp constructor:

static ConstructorHelpers::FObjectFinder<UBlueprint> ZSFSGrenadeBlackHawkBP(TEXT("Blueprint'/Game/AI_Weapons/BlackHawk/SpawnBlackHawk/ZSFSGrenadeBlackHawk.ZSFSGrenadeBlackHawk'"));
	if (ZSFSGrenadeBlackHawkBP.Object){
		
		BHGrenade = Cast<UClass>(ZSFSGrenadeBlackHawkBP.Object->GeneratedClass);
		
	}

in function:

AActor* Grenade = GetWorld()->SpawnActor<AActor>(BHGrenade->GetClass()); 

I get an error:

LogSpawn:Warning: SpawnActor failed because Blueprint is not an actor class

So, if you expose the object type to the editor in some way, you can assign that blueprint class type over to whatever you’re trying to spawn.

Weapon.h
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon Properties")
TSubclassOf<class ABaseProjectile>  ProjectileType;

Weapon.cpp
ABaseProjectile* Projectile = Cast<ABaseProjectile>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, ProjectileType, SpawnTM));

// Modify projectile settings

UGameplayStatics::FinishSpawningActor(Projectile, SpawnTM);

Then in the editor, you can browse whatever class you want to set for the class type
.

You’re retrieving the class from a UClass when you attempt to spawn the actor. A UClass’s class is not an AActor.

In your constructor you’re getting the class you want, and storing it in your BHGrenade property:

if (ZSFSGrenadeBlackHawkBP.Object){
         
    BHGrenade = Cast<UClass>(ZSFSGrenadeBlackHawkBP.Object->GeneratedClass);
         
}

BHGrendade is now the class you want to use to spawn. You don’t need to GetClass from it, it is the class.

Here you’re spawning a object with the class of your class:

AActor* Grenade = GetWorld()->SpawnActor<AActor>(BHGrenade->GetClass());

Try this instead:

AActor* Grenade = GetWorld()->SpawnActor<AActor>(BHGrenade);

Thank you!

I haven’t seen such a method for spawning.

I need just that! Thank you very much!