Set Actor Owner When Spawning

samuelthomson
Thu, 16 Sep 2021 13:53:10 +0000
Blueprint

Hello, I’ve got a ShooterCharacter class (based on the inbuilt Character class) that spawns a custom Gun class on BeginPlay(). I spawn the Gun from the ShooterCharacter, and then on the next line, I set the Gun’s owner to be the ShooterCharacter. I need the gun to have a reference to the ShooterCharacter, because the ShooterCharacter tracks how much ammo is left, and setting the Gun’s owner from the ShooterCharacter that spawns the gun seemed like the most straightforward way to pass on this reference.

My intention was then to use a cast and GetOwner() in the Gun’s BeginPlay() function to get a reference to my ShooterCharacter class and so be able to access the ammo variable in the ShooterCharacter class.

However, this approach doesn’t work, because when I initially run SpawnActor in my ShooterCharacter to spawn the Gun, the gun’s constructor and BeginPlay() functions also run, and at that stage, I still haven’t set the Gun’s owner (that happens in the next line. In any case, running GetOwner() in the Gun’s BeginPlay() function returns nullptr.

I can’t think of another place to set a ShooterCharacter* variable in the Gun to point to the ShooterCharacter, so at this point, I do the full cast (Cast(GetOwner())) whenever I need to check to see if I’ve got any ammo left (i.e. whenever I try to fire my gun).

How inefficient is this, and is there a better way to do this?

2 posts - 1 participant