Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I spawn enemies within a specified random interval?

Tags:

c#

unity3d

I am looking to get enemies to spawn at a random interval between 5 and 15 seconds.

Here is the code I have now. I have the move/transform script on the prefab enemy.

using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {

    public float spawnTime = 5f;        // The amount of time between each spawn.
    public float spawnDelay = 3f;       // The amount of time before spawning starts.        
    public GameObject[] enemies;        // Array of enemy prefabs.

    public void Start ()
    {
        // Start calling the Spawn function repeatedly after a delay .
        InvokeRepeating("Spawn", spawnDelay, spawnTime);
    }

    void Spawn ()
    {
        // Instantiate a random enemy.
        int enemyIndex = Random.Range(0, enemies.Length);
        Instantiate(enemies[enemyIndex], transform.position, transform.rotation);
    }
}

This currently spawns enemies every 3 seconds. How can I spawn an enemy every 5 to 15 seconds?

like image 451
Exilekiller Avatar asked Mar 22 '14 18:03

Exilekiller


People also ask

How do you spawn enemies in game maker?

Also click-and-drag the "Create Instance" icon from "Main1" tab. Choose the enemy you want to spawn from the "Object" drop-down menu and enter the X and Y coordinates where you want the enemy to spawn. Click "OK." Open the room you want the enemies to appear in.


1 Answers

For such a case you might want to make use of a WaitForSeconds call. It is a YieldInstruction which will suspend a coroutine for a certain period of time.

So you create a method to perform the actual spawning, make that a coroutine, and before you do the actual instantiation, you wait for your random period of time. That would look something like this:

using UnityEngine;
using System.Collections;

public class RandomSpawner : MonoBehaviour 
{

    bool isSpawning = false;
    public float minTime = 5.0f;
    public float maxTime = 15.0f;
    public GameObject[] enemies;  // Array of enemy prefabs.

    IEnumerator SpawnObject(int index, float seconds)
    {
        Debug.Log ("Waiting for " + seconds + " seconds");

        yield return new WaitForSeconds(seconds);
        Instantiate(enemies[index], transform.position, transform.rotation);

        //We've spawned, so now we could start another spawn     
        isSpawning = false;
    }

    void Update () 
    {
        //We only want to spawn one at a time, so make sure we're not already making that call
        if(! isSpawning)
        {
            isSpawning = true; //Yep, we're going to spawn
            int enemyIndex = Random.Range(0, enemies.Length);
            StartCoroutine(SpawnObject(enemyIndex, Random.Range(minTime, maxTime)));
        }
    }
}

Give it a try. That should work.

like image 125
Bart Avatar answered Nov 15 '22 10:11

Bart