Hello, the 1st Enemy will come when the game starts.. but I want to call 2nd Enemy when Health 10 is in EnemyHealth script.

public class SpawnerHealth : AbstractHealth
{
private EnemySpawner spawner;
private GameObject enemy2;

public override void TakeDamage(int damageAmount)
{
    base.TakeDamage(damageAmount);
    Debug.Log("Spawner take damage");

    if (Health == 10)
    {
        //  Time.timeScale = 0;
        //SceneManager.LoadScene(2);
    }
}

}

public class EnemySpawner : MonoBehaviour
{
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private float enemyInterval = 5f;
[SerializeField] private GameObject enemy2Prefab;

public Coroutine c1, c2;

private void Start()
{
    c1 = StartCoroutine(spawnEnemy(enemyInterval, enemyPrefab));

    c2 = StartCoroutine(spawnEnemy2(enemyInterval, enemy2Prefab));
}

public IEnumerator spawnEnemy(float interval, GameObject enemy)
{
    yield return new WaitForSeconds(interval);
    GameObject newEnemy = Instantiate(enemy, new Vector3(Random.Range(-2.3f, 2.08f), Random.Range(3.13f, 3.37f)),
        Quaternion.identity);
    StartCoroutine(spawnEnemy(interval, enemy));
}

public IEnumerator spawnEnemy2(float interval, GameObject enemy2)
{
    yield return new WaitForSeconds(interval);
    GameObject newEnemy = Instantiate(enemy2, new Vector3(Random.Range(-2.3f, 2.08f), Random.Range(3.13f, 3.37f)),
        Quaternion.identity);
    StartCoroutine(spawnEnemy(interval, enemy2));
}

}

There are some options:

  • You can make EnemySpawner static so it’s accessible from any script any time (although it might not be the best option because you shouldn’t make everything static in your game).

  • You can pass the EnemySpawner as a parameter to the SpawnHealth and keep a reference to it so you can call any method inside it when health reaches 10.

  • Or you can use delegates. So fancy and clean.