unity-game-enginecinemachine

Cant change ortho size of CM virtual camera from script


I was making an upgrade system for my game that also lets upgrade the zoom level. After the upgrade the total amount is being saved in the playerstats and received from this script. When testing though, the AdjustCameraZoom is being called but nothing changes on the zoom.

using UnityEngine;
using Cinemachine;

public class CameraZoom : MonoBehaviour
{
    public CinemachineVirtualCamera virtualCamera;
    public PlayerStatsSO playerStats;

    private void Start()
    {
        if (virtualCamera != null && playerStats != null)
        {
            AdjustCameraZoom(playerStats.zoomLevel);
        }
    }

    private void AdjustCameraZoom(float zoom)
    {
        var lens = virtualCamera.m_Lens;
        lens.Orthographic = true;
        lens.OrthographicSize = zoom;
        Debug.Log($"Zoom Level Set to: {zoom}");
    }
}

Settings for my Virtual Camera

I added debugs to see how the code behaves in runtime but everything seems fine but no changes are noticeable in the zoom.


Solution

  • I haven't really used Cinemachine. However looking at the documentation the LensSettings type is actually a struct. So your code would not affect the settings of the camera since you copy the struct into a local variable. When you use a local variable, you have to copy the struct back.

    private void AdjustCameraZoom(float zoom)
    {
        var lens = virtualCamera.m_Lens;
        lens.Orthographic = true;
        lens.OrthographicSize = zoom;
        virtualCamera.m_Lens = lens;
        Debug.Log($"Zoom Level Set to: {zoom}");
    }
    

    I don't have the source code at hand, but if m_Lens is an actual field (not a property) you should also be able to do:

    private void AdjustCameraZoom(float zoom)
    {
        virtualCamera.m_Lens.Orthographic = true;
        virtualCamera.m_Lens.OrthographicSize = zoom;
        Debug.Log($"Zoom Level Set to: {zoom}");
    }
    

    Though be warned Unity sometimes does some unexpected things with structs. Specifically the module structs of the ParticleSystem are wrappers which internally hold a reference to the native instance.