How to use "Spawn Actor From Class" node in C++?

Hi, I want to spawn this PickupWeapon actor class in C++, with all of its parameters as shown in the blueprint image.

please correct me what I am doing wrong!

FActorSpawnParameters SpawnInfo;
SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;

TSubclassOf<APickupWeapon> ActorToSpawn = AActor::StaticClass();
ActorToSpawn = GetWorld()->SpawnActor<AActor>(ActorToSpawn, SpawnLocation, SpawnInfo, 0, SpawnID, MyGameInstanceRef->GenerateSN(SN), 1);

FTransform NewTransform;
AMyWeapon* NewWeapon = GetWorld()->SpawnActorDeferred<AMyWeapon>(MyWeaponClass, NewTransform);
if (IsValid(NewWeapon))
{
    NewWeapon-> // Set your initial values here;
    NewWeapon->FinishSpawning(NewTransform);
}
4 Likes

[/quote]

Sir can you look if I am doing it correctly, and how to set collision profile?

FActorSpawnParameters SpawnInfo;
SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
APickupWeapon* NewWeapon = GetWorld()->SpawnActorDeferred<APickupWeapon>(PickupWeapon, SpawnLocation);
if (IsValid(NewWeapon))
{
	FString SN;
	MyGameInstanceRef->GenerateSN(SN);
	NewWeapon->ID = SpawnID;
	NewWeapon->Ammo = 0;
	NewWeapon->SN = SN;
	NewWeapon->Amount = 1;
	NewWeapon->FinishSpawning(SpawnLocation);
}

If you open World.h and look for SpawnActorDeferred, you’ll see this:

SpawnActorDeferred(
	UClass* Class,
	FTransform const& Transform,
	AActor* Owner = nullptr,
	APawn* Instigator = nullptr,
	ESpawnActorCollisionHandlingMethod CollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::Undefined
		)

So you can do
APickupWeapon* NewWeapon = GetWorld()->SpawnActorDeferred<APickupWeapon>(PickupWeapon, SpawnLocation, nullptr, nullptr, ESpawnActorCollisionHandlingMethod::AlwaysSpawn);

You can provide values for Owner and Instigator too, if you want.

1 Like

Thank You Sir very much for this super helpful solution , I really appreciate it :slightly_smiling_face: