Code not working (alternate solution for new Starter Asset camera)

When using the new Starter Asset pack from Unity’s Asset Store, Rick’s code might not work.
For me, it would basically show the zoomedInFOV value for like a micro-second, and then return back to its original state.

Instead, I went with this solution instead:

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

public class WeaponZoom : MonoBehaviour
{
    [SerializeField] CinemachineVirtualCamera fovCamera;
    [SerializeField] float zoomedInFOV = 20.0f;
    [SerializeField] float zoomedOutFOV = 40.0f;
   
    void Update()        
    {
        if(Input.GetMouseButton(1))
        {
            fovCamera.m_Lens.FieldOfView = zoomedInFOV;
        }      

        else
        {
            fovCamera.m_Lens.FieldOfView = zoomedOutFOV;
        }    
    }
}

Let me explain the code in more details.

The Starter Pack asset is using a more advanced Camera system, called Cinemachine.
For that reason, we must add it as a namespace, at the beginning of the script: using Cinemachine;

Then, we add a reference to the camera in our script.
The Cinemachine component is located in the Player prefab, in one of its children, called PlayerFollowCamera

Open your player prefab and search for PlayerCameraRoot > PlayerFollowCamera
There, you will find the component CinemachineVirtualCamera

In this component, look for the attribute called Lens and expand it.
Inside it, there is a value called Vertical FOV
By default, it’s set to 40.
Play with it to see what would be a good zoomedInFOV value (for me, it was 20).

Finally, the gameplay logic code.
In Update() enter the if statement suggested by Rick in his course.
But rather than having a toggle, I used another method called Input.GetMouseButton()
It detects continuously whether the right mouse button is being pressed down, like in old-school Counter-Strike gameplay, where you had to hold the right mouse button.
And finally I added the 2 conditions.

Note that in order to access the FOV value from CinemachineVirtualCamera component, you have to access Lens > Vertical FOV by code, with this value m_Lens field, followed by FieldOfView
Which looks like this: fovCamera.m_Lens.FieldOfView = zoomedInFOV;

Then, simply change that value, based on your GetMouseButton(1) if statement, which looks like this:

if(Input.GetMouseButton(1))
        {
            fovCamera.m_Lens.FieldOfView = zoomedInFOV;
        }
        else
        {
            fovCamera.m_Lens.FieldOfView = zoomedOutFOV;
        }    

Lastly, don’t forget to go in the Inspector and to drag & drop the PlayerFollowCamera prefab into the Player prefab Fov camera field (in the Weapon Zoom script component).

Privacy & Terms