I would like to be able to switch between a variable number of cameras in my scene.
The common approach requires toggling the active camera's 'enabled' property to true and setting the others to false. This is an issue when iterating through the 'Camera.allCameras' array as it doesn't contain the inactive cameras.
I therefore thought that I could get around this by creating a local array of cameras during initialisation and then iterate through that:
using UnityEngine;
using System.Collections;
public class CameraSwitcher : MonoBehaviour
{
int cameraIndex;
Camera[] cameras;
void Start()
{
cameraIndex = 0;
// Assumes that all cameras are initially active in the scene
cameras = new Camera[Camera.allCameras.Length];
int i = 0;
while (Camera.allCameras.Length > 0)
{
cameras[i++] = Camera.allCameras[0];
Camera.allCameras[0].enabled = false;
}
// Does not get recognised as main camera when activated
cameras[cameraIndex].enabled = true;
}
void HandleInput()
{
if (Input.GetKeyDown(KeyCode.F1))
{
cameras[cameraIndex].enabled = false;
cameraIndex = ++cameraIndex == cameras.Length ? 0: cameraIndex;
cameras[cameraIndex].enabled = true;
}
}
void Update()
{
HandleInput();
}
}
The two problems with this approach are:
1) I assume that all cameras in the scene are initially active
2) Setting the camera's 'isenabled' to true in the local camera array does not set the main camera and it therefore remains 'null'
How can I store all the cameras in the scene, regardless of their active status, iterate through the array and set the main camera based on the array index?