How to Reference Actor Components from another Component?
i have an actor with a static mesh component as root component, and from an actor component i want to reference the static mesh so i can apply force and impulse?
Hi!
You can try getting your component’s owner, casting it to your actor class and then getting the component you want from it
Something like this:
UStaticMeshComponent* UMyComponentReference::GetMyMeshFromOwner()
{
AActorComponentReference* owner = Cast<AActorComponentReference>(GetOwner());
return owner ? owner->GetMyMesh() : nullptr;
}
Thanks, it worked, but is it possible to stored in a variable? so i dont have to be casting every time? i tried to stored on a variable, but it doesnt work.
Sure!
YourComponent.h
UStaticMeshComponent* OwnerMesh;
YourComponent.cpp
void UMyComponentReference::BeginPlay()
{
Super::BeginPlay();
OwnerMesh = GetMyMeshFromOwner();
}
In case you want to store the owner as well:
YourComponent.h
class AActorComponentReference* Owner;
UStaticMeshComponent* OwnerMesh;
YourComponent.cpp
void UMyComponentReference::BeginPlay()
{
Super::BeginPlay();
Owner = Cast<AActorComponentReference>(GetOwner());
OwnerMesh = Owner ? Owner->GetMyMesh() : nullptr;
}