Search Unity

NullReferenceException

Discussion in 'Scripting' started by DrexonPl, Mar 26, 2015.

  1. DrexonPl

    DrexonPl

    Joined:
    Mar 19, 2015
    Posts:
    14
    Unity 5.0.0:

    Error:
    Code (csharp):
    1.  
    2. NullReferenceException: Object reference not set to an instance of an object
    3. Unit.Start () (at Assets/Resources/Scripts/Unit.cs:28)
    4.  
    Code:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. public class Unit : MonoBehaviour {
    7.    public static List<GameObject> UnitObjectX = new List<GameObject>();
    8.  
    9.    public Texture2D PMenuIcon;
    10.    public Texture2D PMenuIconRo;
    11.  
    12.    public static Texture2D MenuIcon;
    13.    public static Texture2D MenuIconRo;
    14.  
    15.    public GameObject GUIGhostObjectX;
    16.    public static GameObject ObjectX;
    17.  
    18.    public Material GhostMat;
    19.    public static Material GhostMatStat;
    20.  
    21.    void Start () {
    22.      GhostMatStat = GhostMat;
    23.      ObjectX = GUIGhostObjectX;
    24.      UnitObjectX.Add (ObjectX);
    25.      MenuIcon = PMenuIcon;
    26.      MenuIconRo = PMenuIconRo;
    27.      Menu.UnitIconTextures.Add (PMenuIcon);
    28.      Menu.UnitIconTexturesRo.Add (PMenuIconRo);
    29.      GUIGhostObjectX.AddComponent<Renderer>().material = GhostMatStat;
    30.    }
    31. }
    32.  
     
  2. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    You can see in the error that it points to Unit.cs line 28.

    If you look down to line 28 you can see Menu.UnitIconTexturesRo.Add();

    Menu.UnitIconTexuresRo is null, and that's your problem.
     
  3. DrexonPl

    DrexonPl

    Joined:
    Mar 19, 2015
    Posts:
    14
    in my code 29 is 28 line
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Doesn't change much. In that case Menu.UnitIconTextures is null. It is likely a static variable that is not initialized properly.
     
  5. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    Looks like GhostMatStat is null. Make sure the material is set in your inspector since you're not defining it locally.

    Also, errors like these can be solved 99.9% of the time with a little time spent double checking. The compiler usually knows best. If it says there's a null reference, then that means you're trying to reference and object that is null. So go to the line that it's pointing at and start checking each object reference until you find which is null. For line 29 you'd want to check GUIGhostObjectX and GhostMatStat.

    It's also really good to explain in your initial post what you've tried to do to solve the problem. :)