Choosing from a variety of cameras is a common feature in many genres: race sims, sports sims, tycoon/strategy, and many others. In this recipe, we will learn how to give players the ability of choosing an option from many cameras using their keyboard.
In order to follow this recipe, we have prepared a package containing a basic level named basicScene
. The package is in the folder 0423_02_01_02
.
To implement switchable cameras, follow these steps:
basicLevel
package into your Unity project.basicScene
from the 02_01_02
folder. This is a basic scene featuring a directional light, a camera, and some geometry.cam1
and cam2
.cam2
camera's position and rotation so it won't be identical to cam1
.Switchboard
.cam1
and cam2
.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 (){ int i = 0; for(i=0; i<cameras.Length; i++){ if (Input.GetKeyUp(shortcuts[i])) SwitchCamera(i); } } void SwitchCamera ( int index ){ int i = 0; for(i=0; i<cameras.Length; i++){ if(i != index){ if(changeAudioListener){ cameras[i].GetComponent<AudioListener>().enabled = false; } cameras[i].camera.enabled = false; } else { if(changeAudioListener){ cameras[i].GetComponent<AudioListener>().enabled = true; } cameras[i].camera.enabled = true; } } } }
CameraSwitch
to the Switchboard
game object.1
, 2
, and 3
into the Shortcuts text fields, as shown in the next screenshot.The script is very straightforward. All it does is capture the key pressed and enable its respective camera (and its Audio Listener, in case the Change Audio Listener option is checked).
Here are some ideas on how you could try twisting this recipe a bit.
3.128.200.71