I have four UI Buttons, and there are four different cameras. Is there a way I can press the UI Button to switch the Camera? One button for one camera.
using UnityEngine;
public class NewBehaviour : MonoBehaviour {
public GameObject camera1;
public GameObject camera2;
public GameObject camera3;
public GameObject camera4;
public Texture texture;
void Start() {
camera1.SetActive(true);
camera2.SetActive(false);
camera3.SetActive(false);
camera4.SetActive(false);
}
void OnGUI() {
if(GUI.Button(new Rect(0, 0, 100, 100), texture)) {
camera1.SetActive(true);
camera2.SetActive(false);
camera3.SetActive(false);
camera4.SetActive(false);
}
if(GUI.Button(new Rect(100, 0, 100, 100), texture)) {
camera1.SetActive(false);
camera2.SetActive(true);
camera3.SetActive(false);
camera4.SetActive(false);
}
if(GUI.Button(new Rect(200, 0, 100, 100), texture)) {
camera1.SetActive(false);
camera2.SetActive(false);
camera3.SetActive(true);
camera4.SetActive(false);
}
if(GUI.Button(new Rect(300, 0, 100, 100), texture)) {
camera1.SetActive(false);
camera2.SetActive(false);
camera3.SetActive(false);
camera4.SetActive(true);
}
}
}
It’s very simple, First select your button, next add OnClick function in the button Script (repeat this for each camera you want to active/deactive) drag the camera on One slot, in no function select GameObject → SetActive (bool) an check if you want the camera active or deactive, repeat it for the number of cameras you have
You could do a simple class called CameraManager to control it, something like:
using UnityEngine;
public class Quija_CameraManager : MonoBehaviour
{
public GameObject[] cameras;
public Transform[] startPoints;
public void SetCamera(int index)
{
DisableAndResetCameras();
if (index >= 0 && index <= cameras.Length - 1)
cameras[index].SetActive(true);
}
private void DisableAndResetCameras()
{
if (cameras.Length > 0)
{
for (int i = 0; i < cameras.Length; i++)
{
cameras*.SetActive(false);*
cameras_.transform.position = startPoints*.position;
}
}
}
}
----------
CameraManager Inspector setup:
[160050-simple-camera-manager-inspector-setup.png*|160050]*
----------
UI Button Event setup:
[160051-ui-button-setup-to-control-camera-with-simple-came.png|160051]
_*