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.
Answer by Mrintoxx · May 11, 2020 at 09:56 AM
Maybe you can use a coroutine to spawn ennemies, for me it's a better way to do it.
https://docs.unity3d.com/Manual/Coroutines.html
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) https://learn.unity.com/tutorial/object-pooling
Hope it can help you ;)
Your answer
 
 
             Follow this Question
Related Questions
Highscore not working 0 Answers
RayCast 2d change start position ? 0 Answers
Calculate BoxCollider2D based on the actual player sprite 2 Answers
Unable to save the captured photo in hololens app. 0 Answers
Changing order in layers at runtime with a coroutine 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                