Reputation: 12674
I am writing a game (2D platformer) and I'm trying to get enemies to respawn when the player respawns. I cannot simply reload the level as I have some objects that load when the level loads, so it would cause some problems. Instead, to respawn the player, I have it returned to its starting location (and I handle the lost life and other details).
A player destroys an enemy by hitting it on its head, as follows (in OnTriggerEnter on the player):
if(otherObject.CompareTag("Minion")) //hit by minion
{
if(hitFromTop(otherObject.gameObject)) //if player jumped on enemy
{
otherObject.GetComponent<Minion>().setMoving(false); //stop moving
playSound(KillEnemySound); //play killing enemy sound
jump();
Destroy(otherObject.gameObject); //kill minion
}
//else hurt player
}
As you can see, I destroy the enemy object entirely. In order to maintain which enemies are where, I add them to a list (stored in a separate GameObject) on creation. The list is created in the separate enemy respawning object, as follows:
void Start ()
{
enemyList = GameObject.FindGameObjectsWithTag("Minion");
Debug.Log ("Adding all minions to list");
}
I'm attempting to call a function respawning all minions in the list at their original location by going through the list. The function is as follows:
public void RespawnAll()
{
foreach(GameObject minion in enemyList)
{
Destroy(minion); //make sure to respawn ALL minions
}
Debug.Log ("Respawning all");
foreach(GameObject minion in enemyList)
{
Debug.Log ("instantiating minions from list");
Instantiate (minion, minion.GetComponent<Minion>().origPosition, Quaternion.identity);
}
}
I know that it isn't the most time-optimal method to delete all enemies and respawn them all, and if this logic is wrong or if you know a better way, I'm open to new ideas.
The problem with this idea is, I get an 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.
It seems I'm adding a reference to the existing minion to the list rather than a copy. How can I respawn the enemies properly, at their original position?
Upvotes: 0
Views: 3425
Reputation: 12674
I took Jerdak's advice and, instead of Destroying the enemies, I disabled them. This way, they still existed, and I could loop through and re-enable all of the enemies that were disabled (killed).
Upvotes: 3