0
\$\begingroup\$

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!

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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;

Over in your .cpp

#include "ACharacter.h"

Then in your Begin Play

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; }

// Put your code here
\$\endgroup\$
2
\$\begingroup\$

Use GetOwner() in the component

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .