(Solved): NullReferenceException: Object reference not set to an instance

I’m stuck, the game runs but will not update the score and comes up with this:

NullReferenceException: Object reference not set to an instance of an object
ScoreKeeper.Reset () (at Assets/Scripts/ScoreKeeper.cs:25)
ScoreKeeper.Start () (at Assets/Scripts/ScoreKeeper.cs:13)

Which points to:
private Text mytext;

void Start(){
mytext = GetComponent();
Reset();
}
and:

public void Reset(){
	Debug.Log ("reset");
	score = 0;
	mytext.text = score.ToString();
}

These seem ok, which makes me think I’ve overlooked something in the UI but I can’t seem to find it myself

Including the lines changed from EnemyBehaviour (So you can see it isn’t that):

public int scoreValue = 150;

private ScoreKeeper scoreKeeper;

void Start(){
	scoreKeeper = GameObject.Find("Score").GetComponent<ScoreKeeper>();
}

In OnTriggerEnter2d:

scoreKeeper.Score(scoreValue);

I’m including pictures of the enemy

and the Score

So that hopefully someone can spot what I’m missing

Any ideas or help would be much appreciated

Cheers David

mytext has not been initialised.

If you look at your green screenshot you haven’t dragged it into the Inspector.

1 Like

Thanks for responding so quickly.

I tried moving it across however it still doesn’t update the score.

I also checked the code and mytext was supposed to be set as a private variable not a public one, it’s my mistake that it was there to begin with, Brice manages to get it working as a private variable just fine.

Any other ideas?

1 Like

Your Start() method is also a problem - myText = GetComponent() <- which component? What type?

If you are going to have myText as a private variable then try changing your Start() method to this;

private void Start() {

    myText = gameObject.GetComponent<Text>();
    Reset();
}

If it is the only game object of Type Text this should be ok.

I managed to sort it. I had assigned an older script to the enemyprefab that wasn’t getting updated, so when I changed the script, nothing happened. After changing the script it works fine.

I feel daft now :blush:

Thanks for all your help.

David

1 Like

Hehehe… we have all had a moment like that! :slight_smile:

Glad you got it sorted, well spotted and resolved :slight_smile: