NullReferenceException on scoreboard

The game works well, I have a score of zero and the enemies increase mt score. I do get this error though when I start and another error when I shoot enemies. Using Unity 2018.
image
Scoreboard.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour {

    int score = 0;
    Text scoreText;
    
    // Use this for initialization
    void Start() {
        scoreText = GetComponent<Text>();
        scoreText.text = score.ToString();
    }
    public void ScoreHit(int scorePerHit) {
        score = score + scorePerHit;
        scoreText.text = score.ToString();
    }
}

Enemy.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour {

    [SerializeField] GameObject DeathFx;
    [SerializeField] Transform parent;

    [SerializeField] int scorePerHit = 12;
    ScoreBoard scoreBoard;

	// Use this for initialization
	void Start ()
    {
        scoreBoard = FindObjectOfType<ScoreBoard>();
        AddBoxCollider();
    }

    private void AddBoxCollider()
    {
        Collider boxCollider = gameObject.AddComponent<BoxCollider>();
        boxCollider.isTrigger = false;
    }

    private void OnParticleCollision(GameObject other) {
        scoreBoard.ScoreHit(scorePerHit);
        GameObject fx = Instantiate(DeathFx, transform.position, Quaternion.identity);
        fx.transform.parent = parent;
        Destroy(gameObject);
    }
}

Hi Brenton,

Line 13 is this;

scoreText.text = score.ToString();

That would suggest that perhaps the scoreText object is null, e.g. there is no reference to an object. I see on line 12 you are using GetComponent<Text>, is the Scoreboard.cs script attached to a GameObject that has a Text component?

Privacy & Terms