Search Unity

Object reference not set as an instance of an object

Discussion in 'Scripting' started by canias, Aug 18, 2019.

  1. canias

    canias

    Joined:
    May 7, 2016
    Posts:
    5
    Hi when using the code bellow I get an error saying "Object reference not set as an instance of an object"
    In the editor the public GameObject is set and it has the component I want to acess, I can even modify the contents of the component, however when I try to add it to the Dictionary I get the error. Am I missing something?

    Code (CSharp):
    1.         public SortedDictionary<int, UnitData> SelectableUnits;
    2.         public GameObject unit;
    3.         currentID = 1;
    4.         Debug.Log(currentID);
    5.         UnitData UD = unit.GetComponent<UnitData>();
    6.         SelectableUnits.Add(currentID++, UD);
    7.         Debug.Log(currentID);
     
  2. Deleted User

    Deleted User

    Guest

    You have not initialized your dictionary.
     
    canias likes this.
  3. canias

    canias

    Joined:
    May 7, 2016
    Posts:
    5
    Thanks a ton
     
  4. YetAnotherKen

    YetAnotherKen

    Joined:
    Jun 17, 2019
    Posts:
    30
    1. public SortedDictionary<int, UnitData> SelectableUnits = new SortedDIctionary<>();