Hi,
I’ve tried reading up on null reference exceptions, but there must be something fundamental I’m just not getting. I’m trying to follow the Unity “Space Shooter” tutorial and having some trouble since a lot of the content is outdated. Anyway, I’m on the episode where you create a point counter and my code is giving me a null reference exception and I can’t figure out why. Here’s my abbreviated code for the GameController.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public GameObject hazard;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text scoreText;
public int score;
void Start()
{
score = 0;
UpdateScore();
StartCoroutine (SpawnWaves());
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
}
The part where I get the null reference exception is inside UpdateScore(). Can someone explain why this is happening?