Tuesday, December 2, 2014

Unity: Switch among cameras

Below is the link to a simple demo of how to switch among different cameras in a Unity game:

https://dl.dropboxusercontent.com/u/113201788/Unity3D/Camera.Switch-Camera.zip

Firstly, create two more cameras by selecting "Create->Camera" in the "Hierarchy" panel, name them cam1 and cam2. Change their transform position and rotation in the "Inspector" panel, so that they point to different locations in the scene. Now we have 3 cameras: Main Camera (created by default), cam1, and cam2.

Now create a C# script "CameraSwitch.cs" and update its content as follows:

using UnityEngine;
using System.Collections;

public class CameraSwitch : MonoBehaviour {
 public string[] shortcuts;
 public Camera[] cameras;

 // Use this for initialization
 void Start () {

 }
 
 // Update is called once per frame
 void Update () {
  for(int i=0; i < shortcuts.Length; ++i)
  {
   if(Input.GetKeyUp (shortcuts[i]))
   {
    SwitchCamera(i);
   }
  }
 }

 void SwitchCamera(int index)
 {
  for (int i=0; i < cameras.Length; ++i) 
  {
   if(i==index)
   {
    cameras[i].GetComponent<AudioListener>().enabled=true;
    cameras[i].camera.enabled=true;
   }
   else
   {
    cameras[i].GetComponent<AudioListener>().enabled=false;
    cameras[i].camera.enabled=false;
   }
  }
 }
}

Now create an empty game object named "Switchboard" by selecting "Game Object->Create Empty" in the menu. Attach the "CameraSwitch.cs" to it.

Select cam1 in the "Hierarchy" panel and uncheck its "camera" and "Audio Listener" in the "Inspector" panel. Do the same for cam2. This will make the "Main Camera" visible by default when the game is launched.

Select the "Switchboard" game object in the "Hierarchy" panel, and set the size of "shortcuts" and "cameras" in the "CameraSwitch" to 3 in the "Inspector" panel. Now enter "1", "2", "3" in the "shortcuts" array elements and drag the 3 camera objects from the "Hierarchy" panel into the "cameras" array elements in the "Inspector" panel. That is it. When the game is run, by press one of the keys: "1", "2" or "3", the camera will be switched to one of them.

The code is self-explained, whenever, a user press one of the "shortcuts" keys, only the corresponding camera will be enabled while the other two are disabled.

No comments:

Post a Comment