How to get multiple UCameraComponent References

I have two Camera Components, first one Inherited from C++ base class (ThirdPersonCamera), the other added via blueprints (FirstPersonCamera), this getting parented to my Character mesh on a socket.

When using FindComponentByClass() it’s only returning the “ThirdPersonCamera”. I thought using an array would solve this, but it just returns multiple “ThirdPersonCamera”

So how can I get a reference to my FirstPersonCamera in C++? I need it for starting a line trace from my “FirstPersonCamera”.

This being the array I used.

    UCameraComponent* Camera;
	TArray<UCameraComponent*> CameraArray;

	for (int32 i = 0; i < 2; i++)
	{
		Camera = FindComponentByClass<UCameraComponent>();
		CameraArray.Add(Camera);
	}

	for (int32 A = 0; A < CameraArray.Num(); A++)
	{
		UE_LOG(LogTemp, Warning, TEXT("Name: %s"), *CameraArray[A]->GetName());
	}

FindComponent will always return the first thing it find so you can’t use that way.

You can try something like this

TArray<UActorComponent*> CameraArray = GetComponentsByClass(UCameraComponent::StaticClass());
	for(const UActorComponent* Cam : CameraArray)
	{
		UE_LOG(LogTemp, Warning, TEXT("Name: %s"), *Cam->GetName());

		//You can cast to UCameraComponent
		const UCameraComponent* CamComp = Cast<UCameraComponent>(Cam);
	}

You can also access the current active camera through the player camera manager

APlayerCameraManager* CamManager = UGameplayStatics::GetPlayerCameraManager(GetWorld(), 0);
	CamManager->GetCameraLocation();
	CamManager->GetCameraRotation();
1 Like