Toreole
Toreole

Reputation: 33

Strange NullReferenceException in Unity Script (C#)

The Project works fine, until a certain point is reached, then suddenly it starts throwing NRE's. Here's some source code :

void Start(){
myhealth = GetComponentInChildren<HealthBar>();
    if(myhealth == null)
    {
        Debug.Log("myhealth is null !!"); //It never outputs something here
    }
}

//And Here it works :
public void ApplyDamage(float amount)
{
    myhealth.DamageEnemy(amount);
    if (GetHealth() <= 0)
    { 
       [...]
    }
}

//Then suddenly it throws NRE's here when accesing it from another Script :
 public void AddHealth(float a)
{
    myhealth.HealEnemy(a); //Here
}

public float GetHealth()
{
     return myhealth.GetHealth(); //And here
}

In the HealthBar script there are these variables and these functions:

public float maxHealth;
public float currentHealth;
private float originalScale;

public void DamageEnemy(float giveDamage)
{
    currentHealth -= giveDamage;
}

public void HealEnemy(float heal)
{
    currentHealth += heal;
}

public float GetHealth()
{
    return currentHealth;
}

There doesn't seem to be a reason for the Script to be throwing NRE's, but it still does.

Upvotes: 0

Views: 70

Answers (1)

MX D
MX D

Reputation: 2485

Just like you did in your Start() function, try adding

if(myhealth == null)
{
    Debug.Log("myhealth is null !!");
}

into your

public void AddHealth(float a)
{
    myhealth.HealEnemy(a);
}

leading to

public void AddHealth(float a)
{
    if(myhealth == null)
    {
        Debug.Log("myhealth is null !!");
    }
    else
        myhealth.HealEnemy(a);
}

The myhealth is obtained in the Start() using the myhealth = GetComponentInChildren<HealthBar>(); Which by itself is fine.

But what happens when the child object you got this component from gets destroyed, removed, or deactivated? You might have guessed it, the component no longer exists either.

Upvotes: 1

Related Questions