Spawned actor is always nullptr


I am running into problem with my code. The spawnactor function always return a nullptr. I have tried called it in both BeginPlay and other function and both gave me an nullptr error.

Header file

class AShield* PlayerShield;

TSubclassOf<class AShield> ShieldClass;

And the CPP file

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

	//auto NewShield = GetWorld()->SpawnActor<AShield>(SpawnInfo);

	auto NewShield = GetWorld()->SpawnActor<AActor>(ShieldClass, FVector::ZeroVector, FRotator::ZeroRotator, SpawnInfo);

	NewShield->AttachToActor(this, FAttachmentTransformRules::SnapToTargetIncludingScale);
	NewShield->AddActorLocalRotation(FQuat(FRotator(0.0, -90.0, 0.0)));

	if (NewShield)
		PlayerShield = Cast<AShield>(NewShield);

	bCanShield = true;

The commented out spawn function worked but no mesh. Any thing I can try from here?

Why do you need NewShield? You already have a perfectly fine variable PlayerShield declared, and if you use it right away, you can avoid Casting too:

PlayerShield = GetWorld()->SpawnActor<AShield>(ShieldClass, FVector::ZeroVector, FRotator::ZeroRotator, SpawnInfo);
if (PlayerShield != nullptr)
    PlayerShield->AddActorLocalRotation(FQuat(FRotator(0.0, -90.0, 0.0)));
1 Like

The pointer is still null though, I can’t tell why it is not returning anything.

Just in case, did you set TSubclassOf ShieldClass?

Yes, I added the EditDefaultsOnly in the UPROPERTY and set it up in the BP but for some reason it was still null.

Usually there’s something in the output logs that will explain why… Such as, a collision at the SpawnPoint, etc. The UE Output logs will says something about why it can’t spawn the actor.

If there truly isn’t anything in the logs explaining why you’ll have to step through UWorld::SpawnActor to find the reason.

It can be helpful to temporarily set your solution configuration to “DebugGame Editor”. You can debug without a bunch of optimizations making the instruction pointer jump all over the place. (But check the logs, I’d wager the cause is right there in the output logs.)