Changing between two cameras in an array error

Hi, I have two cameras being stored in an array
var cameraTransform : Transform;
var cameraIndex: int = 1;
var isThirdPerson: boolean = true;

And when the user presses “p” it changes between two cameras using this function

function changeCamera()
{
	if (isThirdPerson == true){
	cameraTransform[cameraIndex].camera.enabled = false; 
	cameraTransform[cameraIndex + 1].camera.enabled = true;
	isThirdPerson = false;
	}
	else if (isThirdPerson == false){
	cameraTransform[cameraIndex + 1].camera.enabled = false; 
	cameraTransform[cameraIndex].camera.enabled = true;
	isThirdPerson = true;
	}


}

But i’m getting the error:
NullReferenceException
UnityEngine.Component.get_transform ()

You will get an error if you:

  1. Failed to allocate space for the array.
  2. Failed to initialize the entries of the array.
  3. If either transform belongs to an game object that does not have its camera variable assigned.
  4. If there are only two cameras, and cameraIndex is anything but 0.

Given that the error is happening with get_transform(), #2 is the most likely.

Since you are just flipping the state for all three of these booleans, you could do somehting like to simplify your code a bit:

#pragma strict

function changeCamera()
{
    cameraTransform[0].camera.enabled = !cameraTransform[0].camera.enabled;
    cameraTransform[1].camera.enabled = !cameraTransform[1].camera.enabled
    isThirdPerson = !isThirdPerson;

}