Instantiate only fi there are less than 5,Instantiate Only if there is less than 5 Gameobject in scene

Hi! So I am kind of new to Unity and C#, and I wonder how you can Instantiate GameObjects if there are less than 5 in the Scene.

Could someone maybe please help me. Thank you!

Here’s the code

void Start()
{
    StartSpawning();
}

void SpawnEnemy()
{
    
    Instantiate (enemyPrefab[Random.Range(0,enemyPrefab.Length)], transform.position, Quaternion.identity);
    
}

void StartSpawning()
{
    InvokeRepeating("SpawnEnemy", spawnTimer, spawnTimer);
}


void StopSpawning()
{
    CancelInvoke();
}

}
,So I am kind of new to Unity and C#, and I wonder how you can Instantiate GameObjects , but only if there is less than 5 already in the Scene

Here is the code:
[SerializeField] GameObject enemyPrefab;
[SerializeField] float spawnTimer = 5f;

void Start()
{
    StartSpawning();
}

void SpawnEnemy()
{
    Instantiate (enemyPrefab[Random.Range(0,enemyPrefab.Length)], transform.position, Quaternion.identity);
    
}

void StartSpawning()
{
    InvokeRepeating("SpawnEnemy", spawnTimer, spawnTimer);
}

void StopSpawning()
{
    CancelInvoke();
}

I assume that some of these are getting destroyed so the number varies. One way is to increment a counter when you instantiate and decrement when you destroy. However, that might mean communicating between game objects, which is straightforward but needs extra code.

An alternative is to instantiate under a parent and count the number of objects the parent has. Just drag the prefab and the parent into fields in the Inspector.

using UnityEngine;

public class Spawner : MonoBehaviour
{
    [SerializeField] GameObject prefab;
    [SerializeField] GameObject parent;

    int maxSpawn = 5;

    private void Update()
    {
        if (parent.transform.childCount < maxSpawn)
        {
            GameObject clone = Instantiate(prefab, Vector3.zero, Quaternion.identity, parent.transform);
        }
    }
}