Search Unity

[SOLVED] NullReferenceExeption - Bug in Unity?

Discussion in 'Scripting' started by sroq, Sep 13, 2015.

  1. sroq

    sroq

    Joined:
    Jun 28, 2015
    Posts:
    13
    Hi All,

    In a script I'm using a static variable from another script. The app works fine, but I get this error message in every update:

    NullReferenceException: Object reference not set to an instance of an object
    HUD.Update () (at Assets/Scripts/HUD.cs:19)

    My scripts:
    Where I declaring the variables:
    Code (csharp):
    1.  
    2. ...
    3. public static int score;
    4. public static int health;
    5. public static int money;
    6. ...
    7. void Start()
    8. {
    9. score = 0;
    10. health = 3;
    11. money = PlayerPrefs.GetInt("Value");
    12. ...
    13.  
    and when I use, the another script:
    Code (csharp):
    1.  
    2. ...
    3. void Update () {
    4. TextScore.text = "" + GameManager.score; //this is the HUD.cs line 19, what seem in the error message
    5. TextHealth.text = "" + GameManager.health;
    6. money.text = "" + GameManager.money;
    7. ...
    8.  
    The last two days I tried to fix this problem, but nothing! I'm a little bit frustrated!

    Thanks a lot!
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    What is TextScore?
     
  3. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,726
  4. sroq

    sroq

    Joined:
    Jun 28, 2015
    Posts:
    13
    TextScore is a UI Text element, what I attached to TextScore in inspector
     
  5. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,726
    You need the class name you declared the static vars in, to be in front of the var.
     
    Last edited: Sep 13, 2015
  6. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Just make a null check for everything on that line e.g. TextScore, to find out which one causes the issue. Besides that, click on the error message. It may happen that you accidentally assigned the script to another game object. By clicking on the error message, the game object that is causing the error message gets highlighted in the hierarchy.
     
    sroq likes this.
  7. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    It's no bug, it means you're referring to an object that doesn't exist. This is a problem with your code, not Unity.

    --Eric
     
    sroq likes this.
  8. sroq

    sroq

    Joined:
    Jun 28, 2015
    Posts:
    13
    MEGA LIKE! I was stupid, as usual, I left the HUD script attached to an earlier game object! I removed that, and everything is fine! Thank you!!!