Exi*_*ler 5 c# unity-game-engine
我希望让敌人以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);
}
}
Run Code Online (Sandbox Code Playgroud)
这目前每3秒产生一次敌人.我如何每隔5到15秒产生一个敌人?
对于这种情况,您可能希望使用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)));
}
}
}
Run Code Online (Sandbox Code Playgroud)
试试看.这应该工作.
| 归档时间: |
|
| 查看次数: |
16437 次 |
| 最近记录: |