如何在指定的随机间隔内生成敌人?

时间:2014-03-22 18:11:21

标签: c# unity3d

我希望让敌人以5到15秒之间的随机间隔产生。

这是我现在的代码。我在预制敌人身上有移动/转换脚本。

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);
    }
}

这目前每3秒产生一次敌人。我如何每隔5到15秒产生一个敌人?

1 个答案:

答案 0 :(得分:6)

对于这种情况,您可能希望使用WaitForSeconds来电。它是一个YieldInstruction,它会在一段时间内暂停一个协程。

因此,您创建一个方法来执行实际的生成,使其成为协程,并在进行实际实例化之前,等待随机的时间段。这看起来像这样:

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)));
        }
    }
}

试一试。这应该有用。