Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

my enemySpawner spawns way too mutch enemies

Discussion in 'Scripting' started by stevenbos655, May 5, 2020.

  1. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class enemySpawner : MonoBehaviour
    6. {
    7.     [SerializeField]
    8.     private float spawnRadius = 7, time = 1.5f;
    9.     public GameObject[] enemies;
    10.     void Start()
    11.     {
    12.        
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         StartCoroutine(SpawnAnEnemy());
    19.     }
    20.     IEnumerator SpawnAnEnemy()
    21.     {
    22.         Vector2 spawnPos = GameObject.Find("Player").transform.position;
    23.         spawnPos += Random.insideUnitCircle.normalized * spawnRadius;
    24.         Instantiate(enemies[Random.Range(0, enemies.Length)], spawnPos, Quaternion.identity);
    25.         yield return new WaitForSeconds(time);
    26.         StartCoroutine(SpawnAnEnemy());
    27.     }
    28. }
    29.  
     
  2. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    I don't get any errors
    I have already tried changing the time value
     
  3. OldenErwanin

    OldenErwanin

    Joined:
    Mar 26, 2020
    Posts:
    31
    Because your Coroutine is in the Update function, which is called every frame. Put that in your Start function
     
    stevenbos655 likes this.
  4. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    thank you i was also wondering how i delete a thread?
     
  5. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,386
    You're calling your coroutine in Update. Remember that Update runs every single frame (60+ times per second), so that means you'll spawn a monster every frame at first. Then each of your coroutines will start more coroutines, so soon you'll be spawning more than one per frame. Try starting your coroutine from Start, which only runs once.
     
  6. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,386
    Threads don't get deleted. they stay up to help other people who may have similar questions.
     
  7. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    ok thx