Search Unity

NullReferenceException creating custom class list through script; C#

Discussion in 'Scripting' started by roguedagger, Jan 18, 2022.

  1. roguedagger

    roguedagger

    Joined:
    Jul 11, 2018
    Posts:
    5
    I've never asked a question here but I've used them for years to find answers, so I apologize if I do this wrong.
    I have been working on a planet simulator, and everything was working fine in the editor, adding planets through a public list or array, but now that I'm going to be dealing with thousands of planets I wanted to speed up the process by reading a document. I want to create a list of my custom class and change it based on the text, then send that list over to another object to implement those classes into real objects. Unfortunately, I get the NullRefrenceExeption error every time I run It. If click the plus button in the inspector, It seems to work fine for whatever amount I added, even If they are completely blank, but as soon as it has to acces it's own it isn't working. I think I'm an intermediate-ish programmer, but I'm mostly self taught and I've never dealt with this... Thank's in advance!

    Error:
    NullReferenceException: Object reference not set to an instance of an object
    SolarSystemHolder.ReadFromTheFile () (at Assets/Scripts/SolarSystemHolder.cs:75)
    SolarSystemHolder.Start () (at Assets/Scripts/SolarSystemHolder.cs:26)

    Here's the guilty code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.IO;
    5. using System.Linq;
    6.  
    7. public class SolarSystemHolder : MonoBehaviour
    8. {
    9.     public List<GameObject> solarSystemArray;
    10.     public GameObject CreatorPrefab;
    11.     public GameObject canvasUi;
    12.     //public TextAsset DATA;
    13.  
    14.     private string[] SystemsNamesArray;
    15.     private string myFilePath, fileName;
    16.     private GameObject obj;
    17.     public List<Planet> PlanetObjs;
    18.  
    19.  
    20.     void Start()
    21.     {
    22.         fileName = "MasterFile.txt";
    23.         myFilePath = Application.dataPath + "/" + fileName;
    24.  
    25.  
    26.         ReadFromTheFile();
    27.  
    28.  
    29.         //canvasUi.GetComponent<UI_Canvas>().addPlanetsAndSystems(solarSystemArray.ToArray());
    30.     }
    31.     public void ReadFromTheFile()
    32.     {
    33.         SystemsNamesArray = File.ReadAllLines(myFilePath);
    34.         PlanetObjs = new List<Planet>();
    35.         foreach (string line in SystemsNamesArray)
    36.         {
    37.             if (line != "")
    38.             {
    39.                 #region
    40.                 if (line.Contains("%"))
    41.                 {
    42.                     obj = Instantiate(CreatorPrefab, transform.position, transform.rotation);
    43.                     obj.transform.parent = transform;
    44.                     obj.name = line.TrimStart('%');
    45.                     //PlanetObjs.Clear();
    46.                     Debug.Log(obj.name);
    47.                 }
    48.                 else if (line.Contains(";"))
    49.                 {
    50.                     solarSystemArray.Add(obj);
    51.                     obj.GetComponent<PlanetSpecsHolder>().makePlanets(PlanetObjs.ToArray());// = PlanetObjs.ToArray();
    52.                     canvasUi.GetComponent<UI_Canvas>().addPlanetsAndSystems(solarSystemArray.ToArray());
    53.                 }
    54.                 #endregion
    55.                 else
    56.                 {
    57.  
    58.                     PlanetObjs.Add(new Planet());
    59.                     int p = PlanetObjs.Count - 1;
    60.  
    61.                     int i = 0;
    62.                     string str = "";
    63.  
    64.  
    65.                     //NAME
    66.                     for (int e = i; e < line.Length; e++) {
    67.                         if (line[e] != '/')
    68.                             str += line[e];
    69.                         else
    70.                         {
    71.                             Debug.Log(str);
    72.                             Debug.Log(PlanetObjs.ToArray().Length);
    73.                             PlanetObjs[p].TransformDetails.name = str;
    74.                             Debug.Log(str);
    75.  
    76.                             str = "";
    77.                             i = e + 1;
    78.                             e = line.Length;
    79.                         }
    80.                     }
    81.                     //SIZE
    82.                     for (int e = i; e < line.Length; e++)
    83.                     {
    84.                         if (line[e] != '/')
    85.                             str += line[e];
    86.                         else
    87.                         {
    88.                             Debug.Log(str);
    89.  
    90.                             PlanetObjs[p].TransformDetails.size = float.Parse(str);
    91.                             str = "";
    92.                             i = e + 1;
    93.                             e = line.Length;
    94.                         }
    95.                     }
    96.                     //DISTANCE
    97.                     for (int e = i; e < line.Length; e++)
    98.                     {
    99.                         if (line[e] != '/')
    100.                             str += line[e];
    101.                         else
    102.                         {
    103.                             Debug.Log(str);
    104.  
    105.                             PlanetObjs[p].TransformDetails.distance = float.Parse(str);
    106.                             str = "";
    107.                             i = e + 1;
    108.                             e = line.Length;
    109.                         }
    110.                     }
    111.                     //SPEED
    112.                     for (int e = i; e < line.Length; e++)
    113.                     {
    114.                         if (line[e] != '/')
    115.                             str += line[e];
    116.                         else
    117.                         {
    118.                             Debug.Log(str);
    119.  
    120.                             PlanetObjs[p].TransformDetails.speed = float.Parse(str);
    121.                             str = "";
    122.                             i = e + 1;
    123.                             e = line.Length;
    124.                         }
    125.                     }
    126.                     p++;
    127.                 }
    128.             }
    129.         }
    130.     }
    131.     private void addPlanet()
    132.     {
    133.         PlanetObjs.Add(new Planet());
    134.     }
    135. }
    136.  
    And here's that custom class I'm trying to create a list of and influence:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5.  
    6. [System.Serializable]
    7. public class Planet
    8. {
    9.  
    10.     [HideInInspector]
    11.     public GameObject PlanetHolder;
    12.  
    13.     [Header("Planet Properties:")]
    14.     public TransEdits TransformDetails;
    15.  
    16.     [Header("Material Style:")]
    17.     public MatProps mats;
    18.  
    19.     [Header("MoonDetails:")]
    20.     public moon Moon;
    21. }
    22. [System.Serializable]
    23. public class MatProps
    24. {
    25.     public Color color = new Color(1.0f, 1.0f, 1.0f, 1.0f);
    26.  
    27.     [Range(0, 1)]
    28.     public float roughness = 1;
    29.     [Range(0, 1)]
    30.     public float smoothness = 1;
    31.     //[Range(0, 1)]
    32.     //public float mountainSize = 1;
    33.     [Range(0, 1)]
    34.     public float metalic = 1;
    35. }
    36. [System.Serializable]
    37. public class TransEdits
    38. {
    39.     public string name;
    40.  
    41.     [Range(0.1f, 150000f)]
    42.     public float size = 0.1f;
    43.     [Range(0, 6000)]
    44.     public float distance = 5;
    45.     [Range(0, 100000)]
    46.     public float speed = 5;
    47.     [Range(0, 90)]
    48.     public float rotation = 0;
    49. }
    50. [System.Serializable]
    51. public class moon
    52. {
    53.     public bool hasMoon;
    54.     [Range(.1f, 1)]
    55.     public float MoonDistance;
    56.     [Range(.1f, 1)]
    57.     public float MoonSize;
    58.     [Range(0, 10000)]
    59.     public float rotTime = 5;
    60. }
    Also (after posting) just realized I should probably have put this in the question area so I'll probably repost it there to.
     
    Last edited: Jan 18, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,738
    Yup yup yup, the answer hasn't changed. The answer is always the same... ALWAYS.

    Why... it's the single most common error ever!!

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

    - drag it in using the inspector
    - code inside this script initializes it
    - some OTHER external code initializes it
    - ? something else?

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.

    Here is a clean analogy of the actual underlying problem of a null reference exception:

    https://forum.unity.com/threads/nul...n-instance-of-an-object.1108865/#post-7137032
     
  3. roguedagger

    roguedagger

    Joined:
    Jul 11, 2018
    Posts:
    5
    Thank you so much! I can't tell you how many hours I spent trying to figure that out! I thought I hadn't initialized planet or something but I debugged every part of PlanetObjs[p].TransformDetails.name and I realized I hadn't initialized the classes INSIDE of Planet(). The new code should be
    public class Planet

    {
    [HideInInspector]
    public GameObject PlanetHolder;
    [Header("Planet Properties:")]
    public TransEdits TransformDetails = new TransEdits();
    [Header("Material Style:")]
    public MatProps mats = new MatProps();
    [Header("MoonDetails:")]
    public moon Moon = new moon();
    }

    Thanks again!
     
    Kurt-Dekker likes this.