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

Enemy Spawner

Discussion in 'Scripting' started by ryanhagedorn, May 20, 2020.

  1. ryanhagedorn

    ryanhagedorn

    Joined:
    May 15, 2020
    Posts:
    5
    What code do I need to add so it repeats this every x seconds. Thanks in advance

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GenerateEnemy : MonoBehaviour
    6. {
    7.     public GameObject theEnemy;
    8.     public int xPos;
    9.     public int zPos;
    10.     public int enemyCount;
    11.  
    12.     void Start()
    13.     {
    14.         StartCoroutine(EnemyDrop());
    15.     }
    16.     IEnumerator EnemyDrop()
    17.     {
    18.         while (enemyCount < 15)
    19.         {
    20.             xPos = Random.Range(-26, 30);
    21.             zPos = Random.Range(-26, 30);
    22.             Instantiate(theEnemy, new Vector3(xPos, 1, zPos), Quaternion.identity);
    23.             yield return new WaitForSeconds(0.1f);
    24.             enemyCount += 1;
    25.         }
    26.     }
    27. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    See how that while loop in your coroutine spawns enemies spaced by 0.1f seconds?

    Basically wrap the entire while loop in ANOTHER endless while loop (usually
    while(true)
    ).

    Inside this new endless while loop, do that existing while loop, and then do a
    yield return new WaitForSeconds(X);
    where X is your X seconds.
     
  3. ryanhagedorn

    ryanhagedorn

    Joined:
    May 15, 2020
    Posts:
    5
    Sorry but I'm new to programming and I don't really understand how to do that. If you could tell me our even write out the code it would be graciously appreciated