- Home /
The question is answered, right answer was accepted
How do I fix this Null Reference error and update my score?
Hello, I'm trying to get my score to update when my enemy is destroyed, but I keep getting a NullReferenceException: Object reference not set to an instance of an object error. I have the following HealthScript attached to my enemy:
public void Damage(int damageCount)//Inflicts damage
{
hp -= damageCount;
if (hp <= 0) {
ScoreScript score = GetComponent<ScoreScript> ();
score.UpdateScore (5);
Destroy (gameObject); //destroy enemy
}
}
Then, I have the following ScoreScript attached to my player:
public void UpdateScore(int scoreToAdd){
score += scoreToAdd;
}
The "score" is a public static int and seems to be recognized as such. What am I doing wrong?
if it's not set... try to debug if you really get the scorescript.
Thanks for the reply thef1chesser. I did a Debug.LogError and am getting the ScoreScript.
Answer by 767_2 · Oct 13, 2014 at 12:26 PM
is store a static int in Scorescript if it is you can do it like that
if (hp <= 0) {
ScoreScript.score+=5;
Destroy (gameObject); //destroy enemy
}
Thanks 767_2. I swear I tried that earlier and at first it didn't want to work. I ended up removing my scripts and re-adding them. Now it's working the way you suggested, so the correct answer award goes to you :)
Answer by Quaker_SDR · Oct 13, 2014 at 12:06 PM
May be the damage fn calls after its destoryed.
Thanks Quaker_SDR, but the damage function is being called after destroy.