I need help for spawning enemies in unity 2d

I have problem spawning enemies in unity 2d. Enemies clones themselves too quickly and it lags. Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner
{
    public Transform[] spawnPoints;
    public GameObject enemy;
    public float spawnTime = 5f;
    public float spawnDelay = 3f; 

    // Use this for initialization
    void Start () {
        InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
    }

    void addEnemy() {
        int spawnPointIndex = Random.Range(0, spawnPoints.Length);
        Instantiate (enemy, spawnPoints[spawnPointIndex].position, 
spawnPoints[spawnPointIndex].rotation);
    }
}

I didn’t type MonoBehaviour because it makes errors when I post this post.

Maybe you can use a coroutine to spawn ennemies, for me it’s a better way to do it.

For example i’m using it to spawn ennemyes prefabs :

IEnumerator Spawner()
    {
        yield return new WaitForSeconds(spawnWait);
        
            while (!stop)
            {
                int randSp = Random.Range(0, transform.childCount);

                    //Spawn Them
                    Instantiate(mb[randMb], new Vector3(Random.Range(-13f,13f), 0, 175), Quaternion.identity);
                    yield return new WaitForSeconds(spawnWait);  

        
            }

        }

If you need to instantiate multiple prefabs and then destroy it better look at object pooling, it stacks the gameobject waiting for reuse it (ex : coins into a runner game)

Hope it can help you :wink: