JS if else basic syntax error.

Alright, first of all I would like to say I am trying to teach myself JavaScript, and have a little knowledge of Python and converting MEL to python. I had spent a few hours on this code and then waited two days to come back to it to see if there was something obvious I wasn’t noticing. I’m sure it is, but I cannot figure it out.

I’m trying to do a basic camera switch. Nothing happens with this code.

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

	}}

But, if I do this for the else, the camera will switch to cam2. The camera will also switch if I leave the else blank. So I’m assuming the code is just going straight to the else if it’s there, and have no idea why.

else {
    cam2.enabled = true;
    cam1.enabled = false;}

Your script works fine for me. Perhaps you have that script on one of the cameras? Do you have any other script that changes the .enabled property.

Here’s what I did.

  • Create a new scene
  • Delete Main Camera
  • Add two new camera objects
  • rename them to cam1 and cam2
  • Changed the background color of cam2 so I could easily see which camera is selected
  • create an empty gameobject called camControl
  • add camtest.js to camControl object
  • drag cam1 and cam2 to their respective slots in the editor for camControl.
  • Press play
  • now the 1 button toggles between the two cameras

camtest.js:

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