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:


but then I tried this and UE4 did crash again:


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

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



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?


#Code For You

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

TArray<UStaticMeshComponent*> Comps;

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

You can easily adapt this code to your own needs




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