Choosing from a variety of cameras is a common feature in many genres: racing, sports, tycoon/strategy, and many others. In this recipe, you will learn how to give players the ability to choose from many cameras by using their keyboards.
For this recipe, we have prepared the BasicScene
Unity package containing a scene named BasicScene
. The package is in the 1362_05_codes
folder.
To implement switchable cameras, follow these steps:
BasicScene
package into a new Project.cam1
and cam2
.cam2
camera's position and rotation so that it won't be identical to cam1
.Switchboard
.cam1
and cam2
. Also, set their Tags as MainCamera, as shown:CameraSwitch
and open it in your editor.using UnityEngine; public class CameraSwitch : MonoBehaviour { public GameObject[] cameras; public string[] shortcuts; public bool changeAudioListener = true; void Update (){ if (Input.anyKeyDown) { for (int i=0; i<cameras.Length; i++) { if (Input.GetKeyDown (shortcuts [i])) SwitchCamera (i); } } } void SwitchCamera (int indexToSelect){ for (int i = 0; i<cameras.Length; i++){ // test whether current array index matches camera to make active bool cameraActive = (i == indexToSelect); cameras[i].GetComponent<Camera>().enabled = cameraActive; if (changeAudioListener) cameras[i].GetComponent<AudioListener>().enabled = cameraActive; } } }
CameraSwitch
to the Switchboard
GameObject.3
. Then, drag and populate the Cameras slots with the cameras from the scene (including the Main Camera, within the Multipurpose Camera Rig | Pivot GameObject) Then, type 1
, 2
, and 3
into the Shortcuts text fields, as shown in the next screenshot:The script is very straightforward. First, it compares the key being pressed to the list of shortcuts. If the key is indeed included on a list of shortcuts, it is passed on to the SwitchCamera
function, which, in turn, goes through a list of cameras, enables the one associated with the shortcut that was received, and also enables its Audio Listener, in case the Change Audio Listener option is checked.
Here are some ideas about how you could try twisting this recipe a bit.
18.189.171.125