Search Unity

Null Reference Exception

Discussion in 'Getting Started' started by GeorgeA7299, Dec 30, 2018.

  1. GeorgeA7299

    GeorgeA7299

    Joined:
    Apr 8, 2017
    Posts:
    32
    Hello I am having problems with the following code:

    Code (CSharp):
    1.  
    2.  
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine;
    6.  
    7. public abstract class Node : MonoBehaviour {
    8.  
    9.  
    10.         public Transform cameraPosition;
    11.  
    12.  
    13.      void OnMouseDown()
    14.             {
    15.             Camera.main.transform.position = cameraPosition.transform.position;
    16.              Camera.main.transform.rotation = cameraPosition.rotation;
    17.         }
    18. }
    19.  
    20.  
    I get the error:

    NullReferenceException: Object reference not set to an instance of an object

    The error is for the line:

    Camera.main.transform.position = cameraPosition.transform.position;


    Can anyone help?
     
  2. ClaudiaTheDev

    ClaudiaTheDev

    Joined:
    Jan 28, 2018
    Posts:
    331
    Is the field cameraPosition assigned in the inspector of editor?
     
  3. GeorgeA7299

    GeorgeA7299

    Joined:
    Apr 8, 2017
    Posts:
    32
    Yes. I set it in the inspector.
     
  4. GeorgeA7299

    GeorgeA7299

    Joined:
    Apr 8, 2017
    Posts:
    32
    I found an answer by searching Google. The problem was that Main Camera needed to have the Tag Main Camera. Thanks anyway.