How to use UE4 get component by class to get a collision component attached via BP

Hey guys sorry if this comes across as a stupid question, Im coming over from Unity and am getting confused on UE4’s version of GetComponent.

I have a sphere collider component attached to a projectile blueprint that I am trying to access via c++. However when I try to do so, the editor crashes.

This is how I am trying to get a refrence to this existing BP component via C++

.h


class USphereComponent* Collision;

.cpp


Collision = this->GetOwner()->FindComponentByClass<USphereComponent>();

Below you can see the collision component attached.

Untitled.png

If anyone could explain to me why this would cause a crash and a potentiol soloution I can use going forward for these types of scenarios I would be very greatful.

1 Like

this-> is redundant as UE4 doesn’t allow shadowing (there is exceptions but generally you don’t need it);

You never stated where you are trying to get the component. If its in the actor then simply:


Collision = FindComponentByClass<USphereComponent>();

is enough to get the sphere component.

Reason your crashing is probably cause you are galling GetOwner() when GetOwner is invalid.

Be warned you CAN NOT use FindComponent or GetComponent inside the Constructor. The earliest place is PostInitializeComponents or BeginPlay.

2 Likes

Thanks, that works perfectly!