Search Unity

NullReferenceException when changing values via script - But still works!

Discussion in 'UGUI & TextMesh Pro' started by code-blep, Aug 24, 2014.

  1. code-blep

    code-blep

    Joined:
    Oct 1, 2010
    Posts:
    308
    Hi

    I am in love with the new UI! Everything is going well but I have found an odd error in the script at the bottom of this post.

    The first line in the Start function generates this error:
    NullReferenceException: Object reference not set to an instance of an object
    uiStats.Start () (at Assets/Scripts/UI/uiStats.cs:12)


    However both the slider and the text get updated fine.

    If I comment out that line, the next line produces the same error and so on. It's been a long day so maybe I am missing something ;)

    Here is the code:
    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4.  
    5. public class uiStats : MonoBehaviour
    6. {
    7.     public Text shieldTextComponent;                              
    8.     public Slider shieldBarDisplay;
    9.  
    10.     // Use this for initialization
    11.     void Start () {
    12.         shieldBarDisplay.minValue = 0;
    13.         shieldBarDisplay.maxValue = 100;
    14.         shieldBarDisplay.value = 50;
    15.         shieldTextComponent.text = "Hello world!";
    16.     }
    17. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Put a
    Code (csharp):
    1. Debug.Log(gameObject.name);
    before the line that causes the error. I bet you a dollar you have that script on another object as well as the one you intended.
     
  3. code-blep

    code-blep

    Joined:
    Oct 1, 2010
    Posts:
    308
    I had looked for that but totally missed it last night, found it straight away this morning, and I should have used debug like that and stopped coding earlier last night ;)

    Thanks StarManta *gives $1*.
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    finally i can retire and quit this life of crime