SetActorLocation Crashing

I’m trying to do an ADS Toggle, I have the Gun as an Actor spawned and childed to the character…

void ACharacter::PostInitializeComponents() {
   Super::PostInitializeComponents();

   UWorld* const World = GetWorld();

   if (Weapon != NULL && World != NULL) {
	ATestWeapon* Wp = World->SpawnActor<ATestWeapon>(Weapon, GunOffset, GunRotation);
	Wp->AttachRootComponentTo(FirstPersonCameraComponent);
   }
}

and then I try to move it with a key press:

void ACharacter::ADSToggle() {
UE_LOG(LogTemp, Log, TEXT("ADS toggled..."));
GunOffset = GunOffset + FVector(1, 0, 0);
ATestWeapon* Wp = Cast<ATestWeapon>(Weapon);
Wp->SetActorLocation(ADSOffset);
}

But when hit RMB for the toggle it crashes. I’ve tried relative location, I’ve tried making the move occur in the weapon class instead. No matter what I do it seems as though trying to move the actor crashes…

Might be related to this line here:

     ATestWeapon* Wp = Cast<ATestWeapon>(Weapon);     

What exactly is “Weapon”? Are you 100% sure it will always be valid? Do you ever assign the spawned “Wp” to your weapon variable?
Try adding a check such as

     if(Wp) Wp->SetActorLocation(ADSOffset);

Weapon is a SubclassOf and is assigned through blueprints to the character. It is actually set the same way projectiles are in the FPS example.

But do you ever assign Wp to Weapon? If you don’t it will be accesing ‘none’ which causes a crash.

  • Doesn’t ATestWeapon* Wp = Cast(Weapon); do that?

Yeah, here:

 ATestWeapon* Wp = Cast<ATestWeapon>(Weapon);
 Wp->SetActorLocation(ADSOffset);

But when you spawn Wp, you never assign the spawned actor to the weapon variable:

ATestWeapon* Wp = World->SpawnActor<ATestWeapon>(Weapon, GunOffset, GunRotation);
 Wp->AttachRootComponentTo(FirstPersonCameraComponent);

See how you never do anything along the lines of Weapon = Wp, or something?

I can’t set Weapon to Wp or *Wp what can a SubclassOf be set to?

Ah, just read your answer more carefully. This is what is happening.
The TSubClassOf in the projectile example is used to specify the class of the spawned projectile, it is not used to store a reference to your weapon. In your case you need create a variable in your header such as:

ATestWeapon* MyWeapon;

Then, after spawning your weapon you assign it to your weapon variable:

MyWeapon = Wp;

Finally, when you move your weapon you simply do the following:

if(MyWeapon) SetActorLocation(blablablabla);

Ah that fixed it… didn’t realize the Weapon variable didn’t hold something.