Respawning enemies on player death

236 Views Asked by At

I have a class, where my enemies spawn at the start of the game. When my player dies, I wanna call the spawn class again to let the enemies spawn again. But when I do so, nothing is happening.

public class EnemySpawn : MonoBehaviour
{

    public GameObject [] Enemies;
    public GameObject [] SpawnClone;
    public Transform [] locations;

    public void Start()
    {
       SpawnClone[0] = Instantiate(Enemies[0], locations[0].transform.position, Quaternion.Euler(0,0,0)) as GameObject; 
       SpawnClone[1] = Instantiate(Enemies[1], locations[1].transform.position, Quaternion.Euler(0,0,0)) as GameObject; 
       SpawnClone[2] = Instantiate(Enemies[2], locations[2].transform.position, Quaternion.Euler(0,0,0)) as GameObject;  
    }
    
}

//other class where I wanna call the Start method again to spawn enemies everytime I die
 private EnemySpawn enemyspawn;
 private void Die()
        {
            m_character.NotifyDied();

            if (m_canRespawn)
            {
                SetVulnerable();
                RemovePoison();
                m_hazards.Clear();
                gameObject.transform.position = m_spawnPosition;
                SetHealth(m_maxHealth);
                enemyspawn.Start();
            }
            else {
                Destroy(gameObject);
            }
        }
1

There are 1 best solutions below

7
Milad Qasemi On

Start method is reserved and is called on the frame when a script is enabled. You should use another method name.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html

You can make it like this, where Spawn is called on Start and is also called on Die method

public class EnemySpawn : MonoBehaviour
{

    public GameObject [] Enemies;
    public GameObject [] SpawnClone;
    public Transform [] locations;

    public void Start()
    {
        Spawn();
    }

    public void Spawn()
    {
       SpawnClone[0] = Instantiate(Enemies[0], locations[0].transform.position, Quaternion.Euler(0,0,0)) as GameObject; 
       SpawnClone[1] = Instantiate(Enemies[1], locations[1].transform.position, Quaternion.Euler(0,0,0)) as GameObject; 
       SpawnClone[2] = Instantiate(Enemies[2], locations[2].transform.position, Quaternion.Euler(0,0,0)) as GameObject;
    }
    
}


public class EnemySpawnCaller : MonoBehaviour
{
    public EnemySpawn enemyspawn;

    private void Die()
        {
        
        enemyspawn.Spawn();

        }
}