Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved Nullreferenceexeption public class X { List<Y> name = new List<Y>(); }

Discussion in 'Scripting' started by Asaioki, Jun 6, 2020.

  1. Asaioki

    Asaioki

    Joined:
    Aug 1, 2016
    Posts:
    43
    Hey there,

    My code is not giving any compile errors but I can't wrap my head around a nullreferenceexception I am getting when trying to .Add (from another class with a parameter that i confirmed not to be null) to the List<Dynasty> dynasties in this class:

    Code (CSharp):
    1. [System.Serializable]
    2. public class CrimeFamily
    3. {
    4.  
    5.     public List<Dynasty> dynasties = new List<Dynasty>();
    6.  
    7.     public CrimeFamily()
    8.     {
    9.  
    10.     }
    11. }
    I am declaring List of class Dynasty inside of the class CrimeFamily.
    but when I use families.dynasties.Add (some Dynasty class that isnt null) in another class it throws a null reference exception.

    even when I add in a method like this:
    Code (CSharp):
    1. public void AddDynasty(Dynasty dynasty)
    2.     {
    3.         dynasties.Add(dynasty);
    4.     }
    when I call that method in another script I get:
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. Family.AddDynasty (Dynasty dynasty) (at Assets/Scripts/Characters/Family.cs:41)


    I am 100% sure it is the list<Dynasty> dynasties throwing the error, but why?

    Edit: also, the Dynasty class is public
    Edit2: the CrimeFamily class is created in a manager monobehaviour class where I create an array (families) of CrimeFamily through the inspector. which can then be accessed by families[0] etc etc..
     
    Last edited: Jun 6, 2020
  2. Asaioki

    Asaioki

    Joined:
    Aug 1, 2016
    Posts:
    43
    I fixed it by adding in
    Code (CSharp):
    1. foreach (CrimeFamily family in families){
    2.      family.dynasties = new List<Dynasty>();
    3. }
    In the same manager class where the Family classes are created through the inspector.