I am a beginer in C# programming and Unity. When building a 2D game using Unity and dealing with scoring, I encountered a null reference exception. The logic of this part of the game is that when the "Asteroid" collides with "Bullet" it will destroy both objects and will add 1 to the score. Below are part of my codes in both "Asteroid" and "Score" script.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Asteroid : MonoBehaviour
{
...
// For Score Supporting
Score score;
...
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.CompareTag("Bullet"))
{
score.AddScore(); // Null Reference Exception occured here.
Destroy(gameObject);
Destroy(coll.gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
[SerializeField]
Text scoreText;
const string scorePrefix = "Score: ";
int score = 0;
void Start()
{
scoreText.text = scorePrefix + score.ToString();
}
public void AddScore()
{
score++;
scoreText.text = scorePrefix + score.ToString();
}
}
I have attached the "Asteroid" script to the gameobject named "Asteroid" and the "Score" script to a canvas named "Score" and populated "scoreText" in the inspector with the text UI named "ScoreText". After debugging I found that when running the OnCollisionEnter2D function, the score object was actually null. What is the problem with my program and how should I solve it?