1
\$\begingroup\$

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.

Enemy box that causes issue

Enemy box that doesn't cause issue

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.

prefab missing from spawner box

\$\endgroup\$
1
  • \$\begingroup\$ Note that you're reassigning the value held by the variable oneLarry in your first function, so it's no longer referring to the prefab. \$\endgroup\$
    – DMGregory
    Dec 31, 2021 at 3:07

1 Answer 1

2
\$\begingroup\$

You are destroying the same oneLarry hence it is giving Missing reference exceptions.

Just seperate prefab and the one you are instantiating like following

[SerializeField] private GameObject oneLarryPrefab;
private GameObject instantiatedOneLarry;

public void SpawnOneLarry() {
    instantiatedOneLarry = Instantiate(oneLarryPrefab, somePosition, someRotation);
}

public void DestroyOneLarry() {
    Destroy(instantiatedOneLarry);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .