C++ GetOwner and GetActorEyesViewPoint on a weapon class

Hi all!

I got a problem with setting GetActorEyesViewPoint in my SGrenadeLauncher class.

In my SCharacter class I do the following:

if (TheGrenadeLauncherWeapon)
	{
		TheSpawnedWeapon = GetWorld()->SpawnActor<AActor>(TheGrenadeLauncherWeapon, FVector(0), FRotator(0));

		const USkeletalMeshSocket* WeaponSocket = GetMesh()->GetSocketByName("WeaponSocket");
		WeaponSocket->AttachActor(TheSpawnedWeapon, GetMesh());
}

In my SGrenadeLauncher.cpp I do this:

void ASGrenadeLauncher::FireWeapon()
{
	AActor* MyOwner = GetOwner();
	MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation); // On this line the editor crashes
}

So the editor crashes on GetActorEyesViewPoint of MyOwner. So something is wrong with MyOwner.

I think either the MyOwner does not find the correct SCharacter Actor, or the MyOwner should be a ACharacter or APawn or something for GetActorEyesViewPoint to work.

In SCharacter.cpp I attached the weapon to the socket. So I would think if I do GetOwner in SGrenadeLauncher.cpp that it would return me the SCharacter as an Actor. So any idea why my code doesn’t work?

Thanks in advance!

You are trying to access a null pointer on line 4 of the cpp, that is why it is crashing. GetOwner() does not contain anything because you have not set the value of Owner.

So when your character picks up or attaches the weapon, make sure to set the owner to your character.

Also protect that pointer. Right before you try to access MyOwner, make sure you put an if statement and check that MyOwner exists first. That will prevent the editor from crashing if for some reason MyOwner is null.

Also once you have the value of owner set, you can move line 3 to begin play and access MyOwner anywhere you need, and that way you are not setting it every time you shoot. But still make sure to protect the pointer at the beginning of fire.

Thanks! works like a charm!

You’re welcome! Glad I could help.