Download

C++ getting components, is there a guide on the different ways to get them?

Hi,
After a ton of digging though code and old forum posts (this shouldn’t be hard) I found a way to get components off my currently possessed actor:



APawn* MyPawn = GetPawn();
	if (!MyPawn) return;

	AActor* MyActor = Cast<AActor>(MyPawn);
	if (!MyActor) return;

	TArray<UActorComponent*> children;
	MyActor->GetComponents(children);
	

	for (int i = 0; i < children.Num(); i++)
	{
		if (children*)
		{
			UActorComponent* child = children*;
			FString name = child->GetName();
			if (child->GetName() == "Hook_BarrelEnd")
			{
				//do something here.
			}
		}
	}


Is there a better way to do this? One of the posts I found said you could grab components of a type by doing this:



	TArray<UChildActorComponent*> children;
	MyActor->GetComponents(children);


Sadly the above fails as it complains that “T template parameter to Get Components must be derived from UActorComponent” (Though UChildActorComponent does derive from UActorComponent). Is there a better way to approach this problem? Any guidance?

2 Likes

Hi and welcome to the UE4 Forums!

The most efficient workflow I know of is to use the templated version!

So if you are looking for the Static Mesh Components of an Actor you can do this:



TArray<UStaticMeshComponent> StaticComps;
YourActor->GetComponents**<UStaticMeshComponent>**(StaticComps);


For those not familiar, this is called passing by reference, in the sense that the function receives your TArray and fills it for you, but only with components that match the type that you supply in the template parameter.

Given your example you might also be interested in this variant!



/* Gets all the components that inherit from the given class with a given tag. */
UFUNCTION(BlueprintCallable, Category = "Actor", meta = (ComponentClass = "ActorComponent"), meta = (DeterminesOutputType = "ComponentClass"))
TArray<UActorComponent*>** GetComponentsByTag**(TSubclassOf<UActorComponent> ComponentClass, FName Tag) const;


Enjoy!

:slight_smile:

Rama

Thanks a lot for taking the time to write this.

It works great if I use the “UStaticMeshComponent” as you did but fails when I use “UChildActorComponent”. Its odd as they both derive from UActorComponent.

I am still getting an error with this code:



TArray<UChildActorComponent*> children;
GetComponents<UChildActorComponent>(children);


But **not **with this code:



TArray<UStaticMeshComponent*> children;
GetComponents<UStaticMeshComponent>(children);


Am I missing something with how UChildActorComponent?

I also just discovered that as the UChildActorComponent is being assigned though the “Add Component” at the blueprint level its not being found as a child in C++. :frowning: