How to use GetComponentByClass / FindComponentByClass?

I’m trying to get a reference of a component (UCameraComponent) from an actor but everytime I use GetComponentByClass or FindComponentByClass and I compile the solution, ue4.5.1 crashes.

I tried this and UE4 didn’t crash:

this->GetComponentByClass(UCameraComponent::StaticClass());

but then I tried this and UE4 did crash again:

(.h)

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Components)
AActor* cameraActor;

I want to set the reference to the cameraActor with the inspector.

(.cpp)

cameraActor->GetComponentByClass(UCameraComponent::StaticClass());

Have you initialised cameraActor? You can’t use a pointer unless it is pointing at something valid or it will crash.

Ah thanks, I did:
cameraActor = nullptr;
but I guess it’s the same as not intitialising it.
What would you suggest if I want to change it in the inspector anyway?

#Solution

#Code For You

Here’s the code I use to get actor components of a specific class:

TArray<UStaticMeshComponent*> Comps;

GetComponents(Comps);
if(Comps.Num() > 0)
{
	UStaticMeshComponent* FoundComp = Comps[0];
       //do stuff with FoundComp
}

You can easily adapt this code to your own needs

:slight_smile:

Rama

4 Likes

Just make sure it’s initialized before you run. Edit your blueprint in the editor, drag a CameraActor into the cameraActor property.