Unity’s Cinemachine: Creating an Interactive Camera using C#
Hello all!
Today, I will go over how to switch cameras and use C# to zoom in and switch targets with the aim feature!
Enabling Cinemachine in C#
You must add the name space “using Cinemachine” at the top of the script or you will not be able to grab components for virtual cameras.
Switching Cameras
When using virtual cameras, you can choose what camera is active by giving them a priority value. The highest value will always be active, but you can always deactivate a camera to give them priority. You can achieve this in C# by grabbing the priority component and changing it there like this:
Zoom
Like when I switched cameras above, you will have to grab the component “CinemachineVirtualCamera” in order to manipulate it’s values.
Make a CinemachineVirtualCamera variable for your camera. I named mine _cam.
- Best practice: call GetComponent in Start since GetComponent can be costly.
Create another int variable named _FOV then set up this If statement in Update:
Since _cam already called GetComponent in Start, you can reach any of CinemachineVirtualCamera’s components here. Grab the FieldOfView component under Lens and assign it a value! Now when I hit Space, it will cycle between a field of view of 60, 40, and 20.
Switching Targets
Now we need to make some targets in the scene to target, assign them to an array, then make another if statement. Some of the work is already finished from the zoom.
Now whenever I hit the R key, I will cycle between the capsule and cube.
That was switching cameras, zoom, and switching targets using C#!
Next up, I will go over Body in virtual cameras.
Thank you for your time!