Unity Camera Toggler C# Script



Are you working with more than one camera in your game?

You can work with any amount of cameras and you can switch between them easily using this very simple C# script, I call it Unity Camera Toggler.

Here is it:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraToggler : MonoBehaviour
{
	
	public GameObject[] Cameras;
	
	int currentCam;
	
    // Start is called before the first frame update
    void Start()
    {
        currentCam = 0;
		setCam(currentCam);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
	
	public void setCam(int idx){
		for(int i = 0; i < Cameras.Length; i++){
			if(i == idx){
				Cameras[i].SetActive(true);
			}else{
				Cameras[i].SetActive(false);
			}
		}
	}
	
	public void toggleCam(){
		currentCam++;
		if(currentCam > Cameras.Length-1)
			currentCam = 0;
		setCam(currentCam);
	}
}

In this script I use array variable of cameras, so no matter how much camera do you want to use, you just add them as much as you need to the scene and refer the script to them.

loading...

2 thoughts on “Unity Camera Toggler C# Script

  1. any advice on making this work with a button toggle instead of the ui element you use here? I want to switch between two cameras with the space key

    1. It’s possible to do it.. just find out about “unity spacebar keycode” then call the function anytime the space key is pressed.

Leave a Reply

Your email address will not be published.