Camera Switching (377647)

Well…

var cam1 : Camera;
var cam2 : Camera;
var cam = 1;
	
function Update () {
	if (Input.GetButtonDown("Camera")  cam == 1) {
		cam1.enabled = true;
		cam2.enabled = false;
		cam = 2;
	}
	if (Input.GetButtonDown("Camera")  cam == 2) {
		cam2.enabled = true;
		cam1.enabled = false;
		cam = 1;
	}
}

This code ought to switch the camera when I press the Camera button, but it doesn’t do anything at all. If I get rid of the block that requires cam to be 2 it will switch once, but I want the button to make it switch back and forth. Why isn’t this working? Thanks!

Try adding the command “return” after the cam = 2; line. So it would look like this:

var cam1 : Camera; 
var cam2 : Camera; 
var cam = 1; 
    
function Update () { 
   if (Input.GetButtonDown("Camera")  cam == 1) { 
      cam1.enabled = true; 
      cam2.enabled = false; 
      cam = 2; 
      return;
   } 
   if (Input.GetButtonDown("Camera")  cam == 2) { 
      cam2.enabled = true; 
      cam1.enabled = false; 
      cam = 1; 
   } 
}

Ah, thanks! Can you explain why I needed that there?

What was happening before was you were first evaluating Input.GetButtonDown("Camera") cam == 1which was true, then switching the camera to 2, and then evaluating Input.GetButtonDown("Camera") cam == 2which was now also true. The second block would execute right after the first every frame the Camera button was pushed. The switch happened back and forth in a single frame, so you never saw anything. The return statement ends the function right then and there, so if the first statement is true it executes that block of code and doesn’t bother with the next statement.
A cleaner (in my opinion) way would be to put the keyword “else” before the second if. That way the second condition is only evaluated if the first is false:

var cam1 : Camera; 
var cam2 : Camera; 
var cam = 1; 
    
function Update () { 
   if (Input.GetButtonDown("Camera")  cam == 1) { 
      cam1.enabled = true; 
      cam2.enabled = false; 
      cam = 2; 
   } 
   else if (Input.GetButtonDown("Camera")  cam == 2) { 
      cam2.enabled = true; 
      cam1.enabled = false; 
      cam = 1; 
   } 
}

An even nicer way to do it would be to nest your conditions:

function Update () { 
	if (Input.GetButtonDown("Camera")) {
		if (cam == 1) {
			cam1.enabled = true; 
			cam2.enabled = false; 
			cam = 2; 
		} else if {
			cam2.enabled = true; 
			cam1.enabled = false; 
			cam = 1;
		}
	}
}

Note that the second camera block doesn’t have a condition before it. If cam does not equal 1, then it must equal 2.

The nesting thing was pretty much what I had at first, but without the else in there, it didn’t work. :wink: Thanks for clearing it up guys!