How do i use GetComponentsByClass() in C++

Could someone please explain to me how to properly use this. I need to get all the static mesh components from an actor. I found the documentation but it really doesn’t explain much to me.

This is the closest I’ve got without causing errors. The only issue is that The array is empty when it should be returning something.

TArray<UStaticMeshComponent*> StaticMeshComps;
TArray<UStaticMeshComponent*>GetComponentsByClass(StaticMeshComps);

for (int y = 0; y < StaticMeshComps.Num(); y++)
{
	UE_LOG(LogTemp, Warning, TEXT("Static Mesh: %s"), *StaticMeshComps[y]->GetName());
}

// Disable all particle components so that they don’t auto fire as soon as the actor is spawned. The particles should be triggered through the particle track.
TArray<UActorComponent*> ParticleComponents = ObjectTemplate->GetComponentsByClass(UParticleSystemComponent::StaticClass());
for (int32 ComponentIdx = 0; ComponentIdx < ParticleComponents.Num(); ++ComponentIdx)
{
ParticleComponents[ComponentIdx]->bAutoActivate = false;
}

I got this from LevelSequenceSpawnRegister.cpp using grepWin, should help you out I hope :slight_smile:

This method did work somewhat the array is no longer empty but the array is of type UActorComponent and not UStaticMeshComponent. This causes an issue because I need to be able to get the location and change the velocity of the components. As the class type is UActorComponent I can’t do anything with it that I need. Is there a way around this or to change the array type to UStaticMeshComponent?
This is my code now.

TArray<UActorComponent*> StaticMeshComps;
StaticMeshComps = actorHit->GetComponentsByClass(UStaticMeshComponent::StaticClass());

for (int y = 0; y < StaticMeshComps.Num(); y++)
{
	UE_LOG(LogTemp, Warning, TEXT("Static Mesh: %s"), *StaticMeshComps[y]->GetName());

	FVector MeshLocation = StaticMeshComps[y]->GetComponentLocation();
}

You probably need to Cast since GetComponentsByClass must by default return UActorComponents.

Just a note though that Im not sure UStaticMeshComponents have their own velocity only when you add a ProjectileComponents and associate those with Mesh Components will they probably have a Velocity (havent looked into it in detail).

 TArray<UStaticMeshComponent*> StaticMeshComps;
 StaticMeshComps = Cast<UStaticMeshComponent>(actorHit->GetComponentsByClass(UStaticMeshComponent::StaticClass()));

As a guess, my C++ is rusty because i avoid using it :slight_smile:

I see where you are getting at with it but it doesn’t work unfortunately I have opened another question about it as this is now slightly off topic but hopefully i can sort it soon. :slight_smile:

Where is the other question?

Brilliant, I’ve been looking for a while for a short answer to this!

I’ve used it before, it’s just that the UE4 documentation is really poor for a refresher.