How to Switch Virtual Cameras Using Only Cinemachine and Scripting in Unity
Objective: To learn a couple of ways we can switch cameras only using Cinemachine and scripting.
Following on the from the article that covered how to switch between cameras using Cinemachine and Timeline, let’s now take a look at how we can switch between Cinemachine virtual cameras NOT using Timeline.
Changing the Priority Field within Unity Editor
In our CinemachineVirtualCamera component that is attached to the virtual camera when you create one, is the field called ‘Priority’:
Priority means which camera is going to be active (or given priority) in the scene, based on the state of the other cameras. By default, all virtual cameras priority is set to ‘10’. If we were to increase this to 11, 12, 13, then this particular virtual camera will have a higher priority than all the other virtual cameras, and will be the active camera in the scene:
E.g. Watch above as all 5 virtual cameras have the same priority of 10. Currently the scene is actively using VCam1, but when we change VCam5 to a priority of 15, you will see that it changes to this virtual camera which now becomes the active one.
We can either set these values directly in the Unity Editor (as shown above) or we can edit this through script. Let’s take a look at how we can make these changes through code.
Changing the Priority Field through Code
To get started let’s make sure we have the Cinemachine namespace so we can access the existing built in classes.
Next, create an empty array called “_cinVCam” which we are going to use to find all game objects with the tag “VCam” (make sure here to add tags to all your virtual camera game objects) and the result will be stored in this array.
From here, let’s check for player input for the keycode ‘R’. Next, we should null check (as best practice) that our arrays length isn’t equal to 0 (meaning that it found some game objects and is storing their information in here). Lastly, let’s have a little bit of fun and use a foreach loop which will cycle through each virtual camera game object, grab it’s component and set the priority value to a random number between 10 and 20.
E.g. In this particular instance the VCam4 had a priority of 18 (being the highest of them all) and as such the new active virtual camera became this one.
Disabling and Enabling Game Objects
By far the easiest approach to all of this is simply by enabling and disabling the virtual camera game objects.
Here I have created a simple array for the virtual camera game objects which I have serialized so I can drag and assign them in the Inspector. Make sure to lock the Inspector tab so you can drag all the virtual cameras into the array:
Let’s detect player input with the ‘R’ key which when pressed will execute the for loop to disable the first 4 virtual cameras, leaving only camera 5 active (as we are looping through the array.Length -1).