I’ve just freshly downloaded UE4 and I’m wondering how I would access the components on a sphere I added to the scene (The physics, collisions etc…) from the code. I’m basically looking for an equivalent to gameObject.GetComponent<RigidBody>()
I’ve looked around and read the manual for help but to no avail. Code snippets would help. Thanks in advance!
Its a bit lengthier than in Unity, because you have to manually cast the result to your component class. However, you can create a templated function yourself to make this shorter to write. For example define this static function:
template<class T>
static T* GetComponentByClass(AActor* Actor)
{
// Checks whether actor is valid before trying to get component
return Actor ? Cast<T>(Actor->GetComponentByClass(T::StaticClass())) : nullptr;
}
And then you can use that function like this, so you have the ease of use as in Unity:
You should check the call stack in Visual Studio to see which line it crashes at. For example, if you look at the implementation of FindComponentByClass<T> it will crash intentionally if T is not a subclass of UActorComponent. It intentionally crashes in this case so that you know right away during development that you’re expecting something from the function that it doesn’t support. Seeing the line it crashes it would reveal the hint.