I have been spending some time trying to make spawning code for my space shooter game. I have been making progress with the code, but my latest error is MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.
This error appears after the enemy in my game has died, so I think what is going on is that the enemy is dying and then my code relies on the enemy being alive. I can’t be sure what code is having trouble with this issue, but I think it is my spawn code. Can someone take a look at this code and tell me how to fix it. And if this code is fine, can someone help give me other ideas for what could be going wrong. Here is my spawn code,
float nextSpawnTime;
[System.Serializable]
public class Wave
public int enemyCount;
public float timeBetweenSpawns;
}
void Start() {
NextWave ();
}
void Update() {
if (enemiesRemainingToSpawn > 0 && Time.time > nextSpawnTime) {
enemiesRemainingToSpawn--;
nextSpawnTime = Time.time + currentWave.timeBetweenSpawns;
spawnpoints = GameObject.FindGameObjectsWithTag ("Spawnpoint");
GameObject spawn = spawnpoints [Random.Range (0, spawnpoints.Length)];
Instantiate (Enemy, spawn.transform.position, spawn.transform.rotation);
}
}
void NextWave()
{
currentWaveNumber++;
print ("Wave: " + currentWaveNumber);
if (currentWaveNumber - 1 < waves.Length)
{
currentWave = waves [currentWaveNumber - 1];
enemiesRemainingToSpawn = currentWave.enemyCount;
enemiesRemainingAlive = enemiesRemainingToSpawn;
}
}
void OnEnemyDeath()
{
enemiesRemainingAlive --;
if (enemiesRemainingAlive == 0)
{
NextWave ();
}
}
}