# In Unreal Engine 4, how do I get the component's "game object" via C++?

I have an ACharacter instance with a weapons component that inherits from UActorComponentattached to it. I'm currently writing code that instantiates a weapon actor and attaches it to the ACharacter instance.

What I'm having trouble with is finding out how to get a reference to the ACharacter from the weapons code. In Unity, this would be a simple this.gameObject or FindComponent<Character> call, assuming the component belongs to the same transform.

Thank you!

To do this in Unreal and C++, you'll need to set a pointer to the class and then cast to it.

Casting is expensive in terms of overhead so if it's something you'll be doing often, it's best to get it sorted in Begin Play and call the variable in Tick or whenever you want to call it.

In the .h file:

class ACharacter;


In whatever section (public, private or protected) is best:

ACharacter* ComponentOwner = nullptr;


#include "ACharacter.h"


ComponentOwner = Cast<ACharacter>(GetOwner());


It is good practise to protect your pointers to avoid crashes. While getting the program working, I'd check here at Begin Play as well:

if (!ComponentOwner)
{
UE_LOG(LogTemp, Warning, TEXT("No ComponentOwner found!");
}


and then in Tick or whatever function is calling the character:

if (!ComponentOwner)
{ return; }


Use GetOwner() in the component