How can i switch between cameras with just clicking a cube, a sphere, any object?

i have 2 cameras and a cube, i want to switch between cameras with a click on the cube

Thank you

Add a new script to the cube with an override of the OnMouseDown() method like follows:

public Camera cameraA;
public Camera cameraB;

void OnMouseDown()
{
  cameraA.enabled = !cameraA.enabled;
  cameraB.enabled = !cameraB.enabled;
}

This assumes you enable only one camera in the editor before starting and that you have a reference to cameraA and cameraB. You just drag them onto the cube in the editor.

Also, this will work on mobile devices as they receive the OnMouseDown event with a finger down.

Let’s say you want to add this behavior to 20 cubes, you don’t want to assign the cameras to every cube, and the cameras don’t exist if you make the cube a prefab, so you could instead attach a more complicated script like this to the cube and it can become a prefab:

static Cameras[] _cameras = null;

void Start()
{
  if (_cameras == null)
    _cameras = GameObject.FindObjectsOfType<Camera>();
}

void OnMouseDown()
{
  foreach (Camera cam in _cameras)
    cam.enabled = !cam.enabled;
}

Now you can support 2 cameras and unlimited cubes. Just make sure the "Camera component of only one actual camera is enabled at startup and all others are disabled. Don’t disable the game object, or it won’t be found with FindObjectsOfType() above. Just disable the “Camera” component.

If you want to go a step further and support more than 2 cameras, you could do the following to loop through them all:

static Cameras[] _cameras = null;
static int _activeCamera = 0;

void Start()
{
  if (_cameras == null)
    _cameras = GameObject.FindObjectsOfType<Camera>();
}

void OnMouseDown()
{
  _cameras[_activeCamera].enabled = false;
  _cameras[(_activeCamera = _activeCamera + 1) % _cameras.Length].enabled = true;
}

Well you get the idea.