I'm making a game where the player fights enemies that spawn at the top of the screen and move down. I have several presets of enemy groups that spawn at once.
The first thing that spawns is one enemy, and later, I want to spawn three of the same prefab at once, which works generally, but if the player kills the first enemy that spawns, the next time the game tries to spawn that enemy, I get the following error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
Here is the code that spawns the enemies.
One instance of the enemy:
void OneLarry()
{
oneLarry = Instantiate(oneLarry, rb.position + Vector2.down * 5.5f, Quaternion.identity);
}
Three instances of the enemy:
void BusyLarry()
{
Instantiate(oneLarry, rb.position + Vector2.down * 5.5f, Quaternion.identity);
Instantiate(oneLarry, rb.position + Vector2.down * 5.5f + Vector2.left * 5f, Quaternion.identity);
Instantiate(oneLarry, rb.position + Vector2.down * 5.5f + Vector2.right * 5f, Quaternion.identity);
}
When the enemy dies, I use:
Destroy(gameObject);
I'm unsure why this isn't working as from my understanding of prefabs, you should be able to destroy one and simply spawn another right afterwards.
This error only occurs for one type of enemy box. All others work as intended, and will spawn again if the player kills one of them.
They are all built in the same way - An empty object with an enemy prefab inside.
Every enemy runs off the same script, which is set to destroy it on death, and the box that contains those enemies destroys itself once it has no children.
Edit: When showing the error to a friend, they noticed that the prefab itself is getting unassigned from the spawner box's list of prefabs. This doesn't happen to any other prefab.
oneLarry
in your first function, so it's no longer referring to the prefab. \$\endgroup\$