Converting Int to String results in NullReferenceException?

Hey Again UnityAnswers.

I’m once again facing a weird problem. I want to display my currentHealth variable on the healthText.text HUD element. Now, my currentHealth is an integer. I’ve tried converting it to a string before changing the UI using ToString();, but this only returns a NullReferenceException error. Now, i know that NullReferenceException means that currentHealth is null, but in Awake() i set currentHealth to startingHealth, which is 100…

Here’s my code. Thanks in advance!

public void TakeDamage (int amount)
	{
		// Set the damaged flag so the screen will flash.
		damaged = true;
		
		currentHealth -= amount;

		currentHealth.ToString ();

		// Set the HUD health string's value to the current health
		healthText.text = currentHealth;
		
		if(currentHealth <= 0 && !isDead)
		{
			// ... it should die.
			Death ();
		}
	}

Integer types are not nullable, unless you make them so.

Therefore, you have one of two problems:

  1. currentHealth is not an integer, but some other nullable type, and it is currently null.
  2. health, or health.text is null.

#2 is the more likely scenario.

In any case, simply calling currentHealth.ToString() doesn’t make currentHealth a string – you need to assign it.

Try the following code, which affords you some robustness:

if (health != null)
    health.text = currentHealth.ToString();
else
    throw new NullReferenceException("Variable health is not set.");

Maybe i am wrong but try:

healthText.text=currentHealth.ToString ();

I am not sure but it should work