Null Reference but Referenced In Editor
I'm working on a C# script that counts my inventory, every item picked up adds to a basic int count. I've done tons of Debug.Log() to check that the item is properly being added and the counts are correct, and all are. However, when I go to set the Text.text of my UI Text object I get a null reference exception. I have tried GetComponent, GameObject.Find (which I hate but had to try) and the normal method on which the Text field is assigned is via a private but serialzed value in the script, and referenced in the editor.
I have done null checks in awake to make sure nothing is changing the values by accident during start, and from the instant runtime is initiated I'm immediately getting a null reference.
[SerializeField]
private GameObject totalSlider;
[SerializeField]
private GameObject totalText;
totalText.GetComponent<Text>().text = string.Format ("{0} / {1}", Count, MaxCap);
totalSlider.GetComponent<Slider>().value = Count;
I have also referenced them directly as and in Editor to expose .text and .value directly, but same results. Have also searched for them in scene by name, without return, and also deleted them and added them again both in and out of the prefab. Checked to make sure it's the objects themselves and not the variables that are nulled, but they are returning values nicely both in and out of debug. Wanted to check to see if there's an obvious mistake I'm making before I email unity directly.
I'm not clear on whats co$$anonymous$$g back null: is it totalText,
totalText.GetComponent() or totalText.GetComponent().text
If the issue is with totalText: can you confirm this GameObject exists at scene start? If the totalText object is created dynamically, after scene start: totalText's value at scene start will always be invalid, until set to the newly created object. Obviously same thing goes for the Text Component attached to the totalText gameobject.
Answer by kloudon716 · Feb 15, 2016 at 08:26 PM
I think you need to initialize totalText to the component and then use it. See below. Same for the slider. and if the component is not on the game object this script is on then you will need to find the object first.
totalText = GetComponent<Text>();
totalText.text = string.Format //etc.
They are both referenced in the editor itself. After hitting play I can still see them attached, but continue getting a null reference.
Your answer
Follow this Question
Related Questions
Unity 2020.1 changing Script triggers complete reimport? 0 Answers
How to save a two-dimensional array, as part of the variable inspector? 0 Answers
Unity editor toggle Sceneviews skybox and effects 0 Answers
Setting instance parent delays scene view update 0 Answers
Array index out of range. But it doesn't appear to be. 2 Answers