Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

"NullReferenceException: Object reference not set to an instance of an ..." when accessing property

Discussion in 'Immediate Mode GUI (IMGUI)' started by Abhinav91, Dec 17, 2014.

  1. Abhinav91

    Abhinav91

    Joined:
    Oct 21, 2013
    Posts:
    67
    Hello,
    I'm a beginner in Editor Scripting. I've written two scripts - 'CalculateStats.cs' and 'CalculateStatsEditor.cs'.
    CalculateStats.cs contains some properties that I've created. CalculateStatsEditor.cs is basically editor script that accesses those properties. Whenever I attach CalculateStats.cs to the MainCamera, I get a NullReferenceException on Line 13 in 'CalculateStats.cs'. If the script was already attached to the MainCamera, each time I click the the script in the Inspector, 2 or 3 NullReferenceExceptions get added in the Console.

    What am I doing wrong?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class CalculateStats : MonoBehaviour {
    5.  
    6.     private string _Name;
    7.     private int _Experience;
    8.     private int _Level;
    9.  
    10.     public string Name
    11.     {
    12.         get{return _Name;}
    13.         set{_Name = value;}
    14.     }
    15.     public int Experience
    16.     {
    17.         get{return _Experience;}
    18.         set{_Experience = 200;}
    19.     }
    20.     public int Level
    21.     {
    22.         get{return _Level;}
    23.         set{
    24.             _Level = _Experience/1000;
    25.         }
    26.     }
    27.  
    28. }
    29.  
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. [CustomEditor(typeof(CalculateStats))]
    6. public class CalculateStatsEditor : Editor {
    7.  
    8.     public override void OnInspectorGUI()
    9.     {
    10.  
    11.         CalculateStats calcStat = (CalculateStats)target;
    12.  
    13.         EditorGUILayout.LabelField("Player Name", calcStat.Name.ToString ());
    14.  
    15.     }
    16.  
    17. }
    18.  
     
    Last edited: Dec 17, 2014
  2. Abhinav91

    Abhinav91

    Joined:
    Oct 21, 2013
    Posts:
    67
    Ok I've fixed the problem. Line 6 in CalculateStats.cs should be

    Code (CSharp):
    1. private string _Name = "";