C# 如何在指定的随机间隔内繁殖敌人?

C# 如何在指定的随机间隔内繁殖敌人?,c#,unity3d,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;

我希望让敌人以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秒产生一个敌人?

在这种情况下,您可能需要使用呼叫。这是一个将在一段时间内暂停协同程序的yield指令

因此,您创建了一个方法来执行实际的繁殖,使之成为一个协同程序,在执行实际的实例化之前,您需要等待随机的一段时间。看起来是这样的:

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

试试看。那应该行。

谢谢。我还在学习,所以我会好好学习代码。