Change Camera – Unity3D (C#)
Switching between multiple cameras is familiar to everybody from racing games. You can get a view from rear, front, interior etc. It’s easy to implement. If you use two or three cameras, you can assign a key to change camera and make them disabled and enabled. If you need more cameras, you need an array to hold them.
At the beginning, we will create an array for cameras. All must be disabled except one at start. We will do this in start function. Then we need an action to change camera on runtime. You may assign any key or mouse button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public Camera[] cameraList; private int currentCamera; void Start () { currentCamera = 0; for (int i = 0; i < cameraList.Length; i++){ cameraList[i].gameObject.SetActive(false); } if (cameraList.Length > 0){ cameraList[0].gameObject.SetActive (true); } } void Update () { if (Input.GetMouseButtonUp(0)){ currentCamera ++; if (currentCamera < cameraList.Length){ cameraList[currentCamera - 1].gameObject.SetActive(false); cameraList[currentCamera].gameObject.SetActive(true); } else { cameraList[currentCamera - 1].gameObject.SetActive(false); currentCamera = 0; cameraList[currentCamera].gameObject.SetActive(true); } } } |
Create three cameras and a cube to test it. In start function, we made all cameras disabled and then made the first one enabled. After that, in update function, we increase the camera index to get next camera. We check if the current camera is the last one in array. If it is, current camera is the first camera in array.
Download source code here. Do not attach this script to any camera! If you do, you cannot reach the script when that camera be disabled.
©Coffee Break Codes – Change Camera – Unity3D (C#)
Pingback: Рецепт: Изменение камеры Unity C#