0

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.

7
  • Is all the code in the fist block on the same script? Commented Oct 2, 2016 at 12:30
  • yes it is. the 2nd block is another script Commented Oct 2, 2016 at 12:44
  • Where do you declare the variable myhealth? Are you using the same instance of the first class when you receive the NRE? Your code above misses some context. In particular the code that calls Start, ApplyDamage and AddHealth Commented Oct 2, 2016 at 12:49
  • a Unity Script (MonoDevelop) Calls the Start() function right when the Object begins to be ingame -> the myhealth variable is always the same from the Start() on and never gets changed Commented Oct 2, 2016 at 13:02
  • Post your HealthBar script Commented Oct 2, 2016 at 13:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.