Untitled

mail@pastecode.io avatar
unknown
csharp
17 days ago
1.6 kB
30
Indexable
Never
public class NewEnemySpawner : MonoBehaviour
{

    public GameObject enemyPrefab;
    public int maxSpawn;
    public float spawnInterval;
    public List<GameObject> enemiesCounter = new List<GameObject>();


    private void Start()
    {

        StartCoroutine(SpawnEnemyTimer());

    }

    IEnumerator SpawnEnemyTimer()
    {

        while (true)
        {

            yield return new WaitForSeconds(spawnInterval);

            if (this.enemiesCounter.Count < maxSpawn)
            {

                SpawnEnemy();

            }

        }

    }

    private void SpawnEnemy()
    {

        if (this.enemiesCounter.Count < maxSpawn)
        {

            GameObject newEnemy = Instantiate(enemyPrefab, randomPosition, Quaternion.identity); //removed randomPosition code for simplicity

            this.enemiesCounter.Add(newEnemy);

            EnemyController enemyController = newEnemy.GetComponent<EnemyController>();
            
            if (enemyController != null)
            {

                enemyController.SetSpawner(this);

            }

        }

    }

    public void EnemyDestroyed(GameObject destroyedEnemy)
    {

        this.enemiesCounter.Remove(destroyedEnemy);

        /*foreach (GameObject enemy in enemiesCounter)
        {

            if (enemy != null && enemy.GetInstanceID() == destroyedEnemy.GetInstanceID())
            {

                enemiesCounter.Remove(enemy);

                break;

            }

        }*/

    }

}