Reputation: 33
im doing a little scene in Unity 3D with multiple cameras
Im trying to make a script to change camera pressing Keys 1,2,3,4,5,6,7,8,9,0
Each number goes to specific camera.
Any help aprreciate.
Thanks.
Upvotes: 1
Views: 5270
Reputation: 103
public GameObject cam1;
public GameObject cam2;
public GameObject cam3;
if (Input.GetKeyDown(KeyCode.Alpha1)) {
cam1.SetActive(true);
cam2.SetActive(false);
cam3.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
cam1.SetActive(false);
cam2.SetActive(true);
cam3.SetActive(false);
}
if (Input.GetKeyDown(KeyCode.Alpha3)) {
cam1.SetActive(false);
cam2.SetActive(false);
cam3.SetActive(true);
}
Upvotes: 0
Reputation: 280
Here is a complete version of a script you can use to switch between cameras
using System.Collections.Generic;
using UnityEngine;
public class CameraSwitch : MonoBehaviour
{
public List<Camera> Cameras;
private void Start()
{
EnableCamera(0);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
EnableCamera(0);
}
else if (Input.GetKeyDown(KeyCode.Alpha2))
{
EnableCamera(1);
}
else if (Input.GetKeyDown(KeyCode.Alpha3))
{
EnableCamera(2);
}
/*
* If you want to add more cameras, you need to add
* some more 'else if' conditions just like above
*/
}
private void EnableCamera(int n)
{
Cameras.ForEach(cam => cam.enabled = false);
Cameras[n].enabled = true;
}
}
Name the script CameraSwitch
(full name CameraSwitch.cs
), create a new GameObject in your scene or use an existing one, add the script to the GameObject (either from the Add Component
menu or just drag-n-drop the script to your GameObject's inspector), then you need to expand property Cameras
by clicking on it in the inspector, set the number of Camera (Size
) to 3, and link your cameras in the following fields. Put the main camera first and don't leave a field blank or the script will fail.
If you need to add a new camera to the list, just add an else if
condition besides the existing ones and don't forget to change the size of your list and link the new cameras in the inspector.
Upvotes: 2
Reputation: 1228
You can use this simple code:
public Camera camera1;
public Camera camera2;
...
void Start()
{
camera1.enabled = true;
camera2.enabled = false;
...
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Alpha1))
{
camera1.enabled = true;
camera2.enabled = false;
...
}
else if(Input.GetKeyDown(KeyCode.Alpha2))
{
camera1.enabled = false;
camera2.enabled = true;
...
}
...
}
You can add other cameras like this. I hope it helps you.
Upvotes: 1