[Cinemachine] Switching between multiple cameras

Running through samyam’s tutorial on Youtube to switch between 2 Virtual Cameras using a state driven camera and it works fine for two cameras, but my scene has three cameras (MainCam, TriCam01, TriCam02) and I don’t understand how to scale it up. Is there a way to either cycle through all available cameras, or to have different buttons switch to different cameras?

using UnityEngine;
using UnityEngine.InputSystem;


public class CinemachineSwitcher : MonoBehaviour
{
	
	[SerializeField]
	
	private InputAction action;
	
	private Animator animator;
	
	private bool MainCam = true;
	

	private void Awake() {
		animator = GetComponent<Animator>();
	}
	
	private void OnEnable() {
		action.Enable();
	}
	
	private void OnDisable() {
		action.Disable();
	}
	
	

    void Start()
    {
		action.performed += _ => SwitchState();      
    }
	
	private void SwitchState() {
		if (MainCam) {
		animator.Play("TriCam01");
		}
		else {
			animator.Play("MainCam");
		}
		MainCam = !MainCam;
	}

}

Maybe you can do this :


public class CinemachineSwitcher : MonoBehaviour
{
    ----------
    private int _idCam = 0; 
    ----------
    private void SwitchState() 
    {

        _idCam = _idCam + 1 > 2 ? _idCam + 1 : 0;

        if (_idCam == 0) 
        {
            animator.Play("MainCam");
        }
        else if (_idCam == 1) 
        {
            animator.Play("TriCam01");
        }
        else if (_idCam == 2)
        {
            animator.Play("TriCam02");
        }
    }
}

Hope it Helps.


Hi @GeroNL , I’m a little confused (as you can probably tell I’m not particularly versed in coding, I’m not making a game, just trying to get a simple scene with camera switches working).

I merged your code in as below, but get the error that The name ‘idcam’ does not exist in the current context.

Do I need add in another private int or bool or something (I don’t quite understand the idcam and _idcam naming).

using UnityEngine;
using UnityEngine.InputSystem;


public class CinemachineSwitcher : MonoBehaviour
{
	
	[SerializeField]
	
	private InputAction action;
	
	private Animator animator;
	
	private int _idCam = 0;

	private void Awake() {
		animator = GetComponent<Animator>();
	}
	
	private void OnEnable() {
		action.Enable();
	}
	
	private void OnDisable() {
		action.Disable();
	}
	
	

    void Start()
    {
		action.performed += _ => SwitchState();      
    }
	
     private void SwitchState() 
     {
         _idCam = idcam + 1 > 2 ? _idCam : 0;
         if (_idCam == 0) 
         {
             animator.Play("MainCam");
         }
         else if (_idCam == 1) 
         {
             animator.Play("TriCam01");
         }
         else if (_idCam == 2)
         {
             animator.Play("TriCam02");
         }
     }

}