Switching Cameras

Hello,
I found a number of threads about this though non of them seems to solve my problem. anywhoo I need to switch between two cameras by pressing a button, heres my script:

var UpDownSpeed : float;
var CombatCamera : Camera;
var NonCombatCamera : Camera;

function Start ()

{


NonCombatCamera.enabled = true;
CombatCamera.enabled = false;


}


function Update () {

if(Input.GetAxis("Mouse Y") > 0){transform.Rotate(-UpDownSpeed, 0 ,0);}
if(Input.GetAxis("Mouse Y") < 0){transform.Rotate(UpDownSpeed, 0 ,0);}


if(Input.GetKey("space") && CombatCamera.enabled == true && NonCombatCamera.enabled == false)
{

CombatCamera.enabled = false;
NonCombatCamera.enabled = true;

}


if(Input.GetKey("space") && NonCombatCamera.enabled == true && CombatCamera.enabled == false)
{

NonCombatCamera.enabled = false;
CombatCamera.enabled = true;

}



}

It works for the first time but after it it wont switch.

Debug.Log is your friend. Spam it everywhere, especially when testing states.

I think you’ll find both if statements are run successively. Make the second an else-if?

Also, it might be a good idea to keep a variable for which camera is selected. If you only have two cameras, a simple solution is:

if (Input.GetKeyDown("space"))
{
    //change the state
    combatCamera = !combatCamera;

    //update objects to match state
    if (combatCamera)
        enableCombat();
    else
        enableNonCombat();
}

Set one camera to be disabled and change the swapping to be:

camera1.enabled = !camera1.enabled;

camera2.enabled = !camera2.enabled;

The first if switches to NonCombatCamera, but then the second if is executed and switches back to CombatCamera. You could place an else before the second if to solve this, but there’s a simpler and better way: just toggle enabled in one of the cameras each time space is pressed, and set the other to its opposite state - both ifs could be replaced by a single one, like this:

if (Input.GetKey("space")){
    // toggle one camera on/off...
    CombatCamera.enabled = !CombatCamera.enabled;
    // and set the other to the opposite state:
    NonCombatCamera.enabled = !CombatCamera.enabled;
}