【问题标题】:How can I spawn enemies within a specified random interval?如何在指定的随机间隔内生成敌人?
【发布时间】:2014-03-22 18:11:21
【问题描述】:

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

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    对于这种情况,您可能需要使用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)));
            }
        }
    }
    

    试一试。应该可以的。

    【讨论】:

    • 谢谢谢谢谢谢。我还在学习,所以我会好好研究代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    相关资源
    最近更新 更多