Download

GetComponent Equivalent of unity3d? n00b question

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!

You can get a component by type from an actor like this:



UMyActorComponent* MyActorComponent = Cast<UMyActorComponent>(MyActor->GetComponentByClass(UMyActorComponent::StaticClass()));


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:



UMyActorComponent* MyActorComponent = GetComponentByClass<UMyActorComponent>(MyActor);


There is already a templated shortcut on AActor its FindComponentByClass<T>()



UMyActorComponent* MyActorComponent = MyActor->FindComponentByClass<UMyActorComponent>();


GetComponentByClass worked when I used it as:

this-&gt;GetOwner()-&gt;GetComponentByClass(UStaticMeshComponent::StaticClass()

However, trying to use
this->GetOwner()->FindComponentByClass<UMyActorComponent>();

Causes the engine to crash.
This is simply on the Cube I pulled from the Basic tab. Any reasons why?

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.

Good to know!

Thank you. How about accessing the components of another actor in the current scene?