Switching between cameras (48945)

I wrote a simple script to switch between cameras.

public var camera : GameObject;

function Start () { }

function Update () {
     if (Input.GetKeyDown (KeyCode.C))
          camera.active = true;
}

Nothing happens when I press C. I am very new to Unity code.
How can I make the camera switch on key?

You have to take into account the two cameras to switch between and make one camera active and the other inactive at the same time.

I never thought of that.

What you see in the viewport is just the image from the first active camera.

I changed the script so Camera2 (Main Camera) would become inactive when Camera1 (Sight Camera) was active. function Start () { Camera1.active = false; Camera2.active = true; } var Camera1 : Camera; var Camera2 : Camera; function Update () { if (Input.GetKeyDown(KeyCode.C)) { Camera1.active = true; Camera2.active = false; } } When the game is started, Camera2 is active while Camera1 is inactive. When I press C, nothing changes.

I changed '.active' to '.enabled' and the script seems to be working now. Thank you for the help.

2 Answers

2

var cam1 : Camera;
var cam2 : Camera;

      function Update () {
      if(Input.GetKeyDown("1")){
      cam1.enabled = true;
      cam2.enabled = false;
      }
     if(Input.GetKeyDown("2")){
      cam1.enabled = false;
      cam2.enabled = true;
     }
     }

Thank you. I believe I found my answer.

You could use this modified version of your script - but don’t attach it to any of the cameras! Add it to some other object - an empty GameObject called CameraSwitcher, for instance:

var Camera1 : GameObject;
var Camera2 : GameObject;

function Start () {
  Camera1.active = false;
  Camera2.active = true;
}

function Update () {
  if (Input.GetKeyDown(KeyCode.C)) { // toggle cameras
    Camera1.active = !Camera1.active;
    Camera2.active = !Camera2.active;
  }
}

active is a GameObject property: if you set camera.active = false;, Unity actually does camera.gameObject.active = false; and print a warning in the console telling you to use camera.enabled instead. It’s better to declare the cameras as GameObjects and use active, because this activates/deactivates all components (very handy, because you can have only one AudioListener active in scene).

Since the GameObject is deactivated, its scripts will not execute Update anymore - that’s why you must attach your script to a 3rd object.

I see. This answers my question. Thank you