Unable to serialize field for CinemachineVirtualCamera

Finally hit my first snag of the course while trying to apply zoom to the Cinemachine Virtual Camera. Feels like it ought to be a simple fix but I can’t quite figure it out.

I’m using this code directly from the lesson video:

[SerializeField] private CinemachineVirtualCamera cinemachineVirtualCamera;

Visual Studio throws an error for the [SerializeField] portion and tells me that “attributes are not valid in this context,” and it throws an error for the private attribute as well.

I’m on Unity 2022.2.0a17.2573, using the 2.9.0-pre.6 version of Cinemachine from the Package Manager.

Can you post your entire code?
Sounds like perhaps you have a extra { or } somewhere
Or maybe you’re trying to define that while inside a function?

Sure. Here’s my full code for CameraController.cs:

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

public class CameraController : MonoBehaviour
{
    private void Update()
    {

        [SerializeField] private CinemachineVirtualCamera cinemachineVirtualCamera;

        // Movement
        Vector3 inputMoveDir = new Vector3(0, 0, 0);
        if (Input.GetKey(KeyCode.W))
        {
            inputMoveDir.z = +1f;
        }
        if (Input.GetKey(KeyCode.S))
        {
            inputMoveDir.z = -1f;
        }
        if (Input.GetKey(KeyCode.A))
        {
            inputMoveDir.x = -1f;
        }
        if (Input.GetKey(KeyCode.D))
        {
            inputMoveDir.x = +1f;
        }

        float moveSpeed = 10f;

        Vector3 moveVector = transform.forward * inputMoveDir.z + transform.right * inputMoveDir.x;
        transform.position += moveVector * moveSpeed * Time.deltaTime;


        // Rotation
        float rotationSpeed = 100f;

        Vector3 rotationVector = new Vector3(0, 0, 0);

        if (Input.GetKey(KeyCode.Q))
        {
            rotationVector.y = +1f;
        }
        if (Input.GetKey(KeyCode.E))
        {
            rotationVector.y = -1f;
        }

        transform.eulerAngles += rotationVector * rotationSpeed * Time.deltaTime;

        // Zoom

        Debug.Log(Input.mouseScrollDelta);

        CinemachineTransposer cinemachineTransposer = cinemachineVirtualCamera.GetCinemachineComponent<CinemachineTransposer>();

        if (Input.mouseScrollDelta.y > 0)
        {
            cinemachineTransposer.m_FollowOffset = new Vector3(0, 1, -10);
        }
    }
}

You were exactly right - looks like I was trying to serialize the camera inside the Update() method instead of before it. Thanks!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms