Having trouble with GetComponentByClass in version 4.21 or higher?

Hopefully this saves future adventurers through this class the trouble I went through:

I’m using Unreal 4.21 and taking this class for the first time. I was having trouble getting the assignment to PhysicsHandle working, so I dug into the documentation. It looks like the GetComponentByClass function is no longer templated, so in order to get it to compile and function correctly, my code now reads:

PhysicsHandle = (UPhysicsHandleComponent*)(
    GetOwner()->GetComponentByClass(UPhysicsHandleComponent::StaticClass())
);

I’m not sure why they moved from a templated version (probably compile times?) but as a result, there is type-erasure (GetComponentByClass returns a UActorComponent*), hence why I am required to cast the result.

GetComponentByClass simply calls FindComponentByClass and provides the UFUNCTION annotation so that it can be used from Blueprints. I believe the reason for doing this is that in newer versions of UE4, Epic tries to no longer expose virtual functions directly to Blueprints.

In C++ you can call the template version of FindComponentByClass directly:

PhysicsHandle = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>();

Awesome! That is a nicer solution. Nevertheless, I’m glad this thread is here now because the function name is different from what it was in the lecture video.

1 Like

Privacy & Terms