- Home /
Getting Null Object Reference even though I'm not referencing an object
So I'm trying to use the unity ui text and it works fine except for recently I've been getting error saying I have a null object reference on the line where I define my statTextHealth variable even though I don't reference any other object throughout the entire script
public int playerMaxHealth;
public double playerCurrentHealth;
public double defense;
public double strength;
private Text statTextHealth;
private Text statTextDefense;
private Text statTextStrength;
void Start () {
playerCurrentHealth = playerMaxHealth;
}
void Update () {
//This line right below this comment is the line the error is directing me to
statTextHealth.text = ("Health: " + playerCurrentHealth.ToString());
statTextDefense.text = ("Defense: " + defense.ToString());
statTextStrength.text = ("Strength: " + strength.ToString());
if (playerCurrentHealth <= 0) {
gameObject.SetActive(false);
}
}
public void PlayerDamage(int damage) {
playerCurrentHealth -= ((double)damage / defense);
}
public void PlayerHeal(int heal) {
playerCurrentHealth += heal;
if (playerCurrentHealth > playerMaxHealth)
playerCurrentHealth = playerMaxHealth;
}
NullReferenceException: Object reference not set to an instance of an object CharStatManager.Update () (at Assets/Scripts/PlayerCharacterScripts/CharStatManager.cs:22)
Answer by Commoble · Feb 25, 2018 at 12:49 AM
Your statTextHealth is null; you must assign an instance of Text to it before you can access fields from it
I would suggest making it public and assigning your Text to it in the inspector, if possible
Your answer
![](https://koobas.hobune.stream/wayback/20220612153352im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Null reference when I already assign a value? (UI Button and Text) 1 Answer
UI 4.6 Text - Bad call to Text or bug? 1 Answer
Graphic problem with UI Text 2 Answers
New UI: change text 2 Answers