NullReferenceException: Object reference not set to an instance of an object. (Cameras switching)

Hi!
I want to make script that will change camera on “E” button when player is standing in trigger, but when I change Camera to Car camera (CCamera) then this error is displaying.
Please help, thank you!

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

public class Auto : MonoBehaviour
{
    void Start()
    {
        var FPSCamera = GameObject.FindGameObjectWithTag("MainCamera");
        var CCamera = GameObject.FindGameObjectWithTag("CCamera");
        CCamera.SetActive(false);
        FPSCamera.SetActive(true);
    }
    void OnTriggerStay(Collider other)
    {
        var FPSCamera = GameObject.FindGameObjectWithTag("MainCamera");
        var CCamera = GameObject.FindGameObjectWithTag("CCamera");
        if (Input.GetKeyDown(KeyCode.E))
        {
            CCamera.SetActive(true);
            FPSCamera.SetActive(false);
        }
    }
}

**Hi @IamJarek . First of all put your cameras in the ‘Hierarchy’. **

1. Here we will need two public variables of type GameObject.

public class Auto : MonoBehaviour
 {
    //Declare two public variables of type GameObject & we will drag our cameras in the inspector.
    public GameObject FPSCamera, CCamera;

     void Start()
     {
       //Here you do not need to FindGameObjectWithTag.
       //We will drag our cameras directly onto our Inspector.
       //Then we will perform SetActive(); statements.
         CCamera.SetActive(false);
         FPSCamera.SetActive(true);
     }

     void OnTriggerStay(Collider other)
     {
       //Here also we don't need to FindGameObjectWithTag.

       //Now we will check if & only if our Player is touching/staying in our collider.
         
      if(other.tag == "Player")
      {
         //And finally if & only if our player is touching/staying in the collider.

         if (Input.GetKeyDown(KeyCode.E))
         {
            //And as we'll press 'E' then we got to perform SetActive(); statements here.

             CCamera.SetActive(true);
             FPSCamera.SetActive(false);
         }
       }
  }
}

2. Just make sure to assign a tag to your player with a tag - “Player” (Case Sensitive as we are using it in our script).

See Image
98790-tag-info.jpg

If the ‘Player’ tag isn’t available then you can create one using ‘Add Tag’ option down there.

3. Now you can attach this script to your desired GameObject and then Drag your cameras from hierarchy (FPSCamera and CCamera) respectively into the script component of your GameObject in the Inspector. See Image Below!

Drag your FPSCamera & CCamera respectively from the Hierarchy only (not from prefabs)
98792-dragyourcamerahere.jpg

4. Now give it a try.!

Hope it will work.!