Spaget09onYt
Spaget09onYt

Reputation: 3

I am trying to change the fov of my camera when left control is pressed, but it won't work

using System.Collections.Generic;
using UnityEngine;

public class FOVCameraChange : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.LeftControl)){
            Debug.Log("DOWN");
            Camera.main.fieldOfView = 120;
        }
        else {
            Debug.Log("UP");
            Camera.main.fieldOfView = 60;
        }
    }
}

The error I am getting is "Object Reference not set to an instance or an object."

I am trying to make the camera fov double when you press control.

Upvotes: 0

Views: 39

Answers (1)

ipodtouch0218
ipodtouch0218

Reputation: 3346

Camera.main returns the first (enabled) camera that has the tag "MainCamera". Since it's throwing an NRE, you must not have a camera with that tag within your scene. Either give your camera the "MainCamera" tag, or make a Camera variable and set it through the editor, the same as you would do any other variable:

public class FOVCameraChange : MonoBehaviour
{
    [SerializeField] private Camera camera;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.LeftControl)){
            Debug.Log("DOWN");
            camera.fieldOfView = 120;
        }
        else {
            Debug.Log("UP");
            camera.fieldOfView = 60;
        }
    }
}

Unity Scripting API: Camera.main

Upvotes: 0

Related Questions