unity 3d student

Switching Cameras at runtime

switching cameras in Unity
Hi all I’ve had a few requests for this and i’m currently away from my video recording rig for the festive holidays so here’s a quick written example!

In order to switch cameras you’ll simply be disabling one and enabling another. In this example, I have created a simple scene with a cube, and 3 cameras. To identify these objects and run through them, instead of finding each name in turn, we can use tagging to select the camera objects all at once in a list, then use a for loop to iterate through the list of them, finding the camera component and disabling them all, then enable the required camera. Let’s break that down a bit more simply -

I. Create a keypress that calls a custom function with an argument of an integer number, so the corresponding key can be assigned to which numbered camera to select, for example -

  1. function Update(){
  2.    if(Input.GetKey("1")){
  3.   Debug.Log("Using Camera One");
  4.   camSwap(1);
  5.    }
  6. }
  7. function camSwap(currentCam : int){
  8.  
  9. }

II. Then within the camSwap function, create a For loop to find all objects with a particular tag – in my example I made a tag called ‘cam’ and applied it to all 3 camera objects – and iterate through them, disabling the Camera components in each using GetComponent -

  1. function camSwap(currentCam : int){
  2.  var cameras = GameObject.FindGameObjectsWithTag("cam");
  3.  
  4.  for (var cams : GameObject in cameras){
  5.   cams.GetComponent(Camera).enabled = false;
  6.  }
  7. }

III. Finally, after the for loop, select the camera you DO want and enable it by creating a string of text consisting of the word Camera and the number from the currentCam argument in it*, and then using Find and GetComponent to select the object, then enable its Camera component -

  1. var oneToUse : String = "Camera"+currentCam;
  2.  gameObject.Find(oneToUse).GetComponent(Camera).enabled = true;

* remember that for this to work, you’ll need to name your cameras Camera1, Camera2, Camera3 and so on.

Here is a full look at the script, and also refer back to the image at the top to understand how i’ve setup my objects and tagged them.

Javascript

  1. function Update () {
  2.  if(Input.GetKey("1")){
  3.   Debug.Log("Using Camera One");
  4.   camSwap(1);
  5.  }
  6.  if(Input.GetKey("2")){
  7.   Debug.Log("Using Camera Two");
  8.   camSwap(2);
  9.  }
  10.  if(Input.GetKey("3")){
  11.   Debug.Log("Using Camera Three");
  12.   camSwap(3);
  13.  }
  14. }
  15.  
  16. function camSwap(currentCam : int){
  17.  var cameras = GameObject.FindGameObjectsWithTag("cam");
  18.  
  19.  for (var cams : GameObject in cameras){
  20.   cams.GetComponent(Camera).enabled = false;
  21.  }  
  22.  
  23.  var oneToUse : String = "Camera"+currentCam;
  24.  gameObject.Find(oneToUse).GetComponent(Camera).enabled = true;
  25. }

C# Equivalent

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class camControl : MonoBehaviour {
  5.  
  6.  void Update () {
  7.   if(Input.GetKey("1")){
  8.    Debug.Log("Using Camera One");
  9.    camSwap(1);
  10.   }
  11.   if(Input.GetKey("2")){
  12.    Debug.Log("Using Camera Two");
  13.    camSwap(2);
  14.   }
  15.   if(Input.GetKey("3")){
  16.    Debug.Log("Using Camera Three");
  17.    camSwap(3);
  18.   }
  19.  }
  20.  
  21.  void camSwap(int currentCam){
  22.   GameObject[] cameras = GameObject.FindGameObjectsWithTag("cam");
  23.  
  24.   foreach (GameObject cams in cameras){
  25.    Camera theCam = cams.GetComponent<Camera>() as Camera;
  26.    theCam.enabled = false;
  27.   }  
  28.  
  29.   string oneToUse = "Camera"+currentCam;
  30.   Camera usedCam = GameObject.Find(oneToUse).GetComponent<Camera>() as Camera;
  31.   usedCam.enabled = true;
  32.  }
  33. }

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

15 Comments

    Well I’m programmer and I am trying to learn about unity to develop games, but I think that there’s a lot of weird things with the Unity3d Scripting.

    I would love to see some tutorials about how to create dynamically elements using scripting, all the scripting reference of the unity is weird, it’s not like a real programming. I think it’s natural to programmers to think that GUIText extends the GameObject Object.

    But what I see is that I have to create a GameObject at first and after that I’ll have to add properties to that. Why I cant just type?

    GUIText : GUIText = new GUIText();

    This site is pretty cool, thanks for the lessons.

  • Mxyzpltk you can do that but you will need to use the a line a little more like
    var myGUIText : GUIText = new GUIText();
    The compiler will not complain because it is perfectly legal code but I think what you are looking for is the Instantiate() function and prefabs.

  • Mxyzpltk you can do that but you will need to use the a line a little more like
    var myGUIText : GUIText = new GUIText();
    The compiler will not complain because it is perfectly legal code but I think what you are looking for are the Instantiate() function and prefabs.

  • My question about cameras is whether I can have them overlay using Unity. e.g to have a rear view mirror in a driving game.

  • Just want to thank you for this wicked resource you are providing for us budding Unity’ers. Couldn’t get my head around taging or “FindGameObjectsWithTag”, which I need to use in another unrelated project, but after working through this example it all became clear :)

    Nice 1

  • Will, Another great tutorial, thank you very much and keep up the great work!

    @AJGP:
    You can absolutely position camera output over another, but the reason it won’t be very good for your example is that you can’t make the camera output be any shape other than a rectangle. Combine this with the fiddliness of putting imagery above the output to make it LOOK like a mirror and you’ll find that what you’re looking for is the Target Texture feature.

    What that feature does is allow you to make the output of a camera render onto a texture directly, so for the mirror, you would simply make the model (which would look good), then apply the camera rendered texture to the “glass” portion of the mirror and that’d do it.

  • Will – This is a really useful tutorial, as usual. Thanks!

    I just want to confirm my understanding of your answer to AJGP regarding a rearview mirror – wouldn’t the Target Texture solution require Unity Pro? I know I use a similar technique for the fisheye lens, and it requires Pro.

  • Sorry, I see that was Krister’s answer.

    And I just checked the documentation – It is a Pro feature.

    AJGP and others should check http://unity3d.com/support/documentation/Components/class-Camera.html

    At the bottom of the page is an example of using this for a live arena monitor, and the note that it can be used for “sports arena video monitors, surveillance cameras, reflections etc.”

  • Hello,
    this is a camera switching code, if you do not switch the camera, instead switching like cubes, spheres, how to rewrite the code?

    • Sorry not sure I understand the question.. you want to switch using an object.. how do you mean, clicking? collision?

    then simply u can use the LookAt() to make a switching between Cubes with one Camera.

  • Thanks for this, just what I was looking for.

  • Hello! I am a new Unity user and I am really enjoying these tutorials. I have a question about this tutorial. I need to write a script wherein when a certain event happens the game switches from the main Camera following the character to a secondary camera looking at the new event happening (like a previously locked door opening). Any ideas? Thanks!

    Dwayne

    • Hi Dwayne, just use GetComponent to enable one camera and disable another. Or just establish public vars of just the cameras, and then switch em in script eg.

      var cam1 : Camera;
      var cam2 : Camera;

      if(cutscene){
      cam1.enabled = false;
      cam2.enabled = true;
      }else{
      cam1.enabled = true;
      cam2.enabled = false;
      }

    Why is it that Debug.Log will only print each item one time? Is there any way to remove this limit?

    For example:

    function Update(){
    if(Input.GetKey(“1″)){
    Debug.Log(“1 pressed”);
    if(Input.GetKey(“2″)){
    Debug.Log(“2 pressed”);
    }

    If I press 1,2,1 I should get

    1 pressed
    2 pressed
    1 pressed

    The third line is omitted.

Leave a Comment