- Home /
The question is answered, right answer was accepted
Trying to increase score when enemy is hit
I have a game where you hit and enemy with an arrow, it takes 1 damage which reduces its health by 1. now i, trying to add a score system so when you hit the enemy you also gain a point. But with my current code i an getting "NullReferenceException: Object reference not set to an instance of an object".
This script is attached to the text object i have on the canvas:
public class PlayerScore : MonoBehaviour { public int score = 0;
void Update ()
{
GetComponent<Text>().text = "Score: " + score;
}
}
And this script is on the enemy: public class ArrowDamage : MonoBehaviour {
private PlayerScore score;
void Awake ()
{
score = GameObject.Find("ScoreText").GetComponent<PlayerScore>();
}
void OnTriggerEnter (Collider Enemy)
{
if (Enemy.gameObject.CompareTag("Enemy"))
{
Enemy.GetComponent<NPC>().Health --;
Enemy.GetComponent<PlayerScore>().score ++;
}
} }
The error refers to Enemy.GetComponent().score ++;
I have a feeling the problem is that it is trying to find PlayerScore on the Enemy rather than the object with the text on it but i'm not sure what to do.
Answer by Glurth · Mar 24, 2018 at 05:13 PM
Enemy.GetComponent<PlayerScore>().score ++;
should probably be:
score.score++;
(assuming the Awake function can actually find the PlayerScore object.)
This looks weird because you named both the PlayerScore inside ArrowDamage, and the integer inside PlayerScore, with the same name: "score".
Wow that actually works, i cant believe it was so simple.
Follow this Question
Related Questions
NullReferenceException 0 Answers
Device Simulator - Null Reference Error 0 Answers
NullReferenceException - Why? 2 Answers
NullReferenceException, still the code is working? 2 Answers