我想知道如何以随机速度产生敌人。我在互联网上环顾四周寻找解决方案,但似乎没有一个接近(或者我看起来还不够,我不确定。如果有解决方案的话)在某处,请分享它。)
如果我可以在游戏开始一段时间后开始随机化速度,那也很棒。
我目前有以下代码。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnEnemies : MonoBehaviour {
//Variable to store the enemy prefab
public GameObject Enemy;
//Array to store the spawn points
public Transform[] SpawnPoints;
//Variable to countdown the time for each spawn so that more enemy prefabs can spawn
public float SpawnTimer = 5.0f;
//Variable to store amount of original enemies spawned at the start of the game
private int nEnemies = 1;
//Variable to store the previous spawn time
private float prevSpawnTime = 1f;
//Variable to store the spawn delay time
private float delay = 0f;
//List to store the number of spawn points
List<int> spoints = new List<int>();
//Update called once per frame
void Update()
{
//Variable to store the delayed spawn time, where the delayed spawn time equals to the current time since the game has started minus the previous spawn time
float dt = Time.time - prevSpawnTime;
//If the delayed spawn time is more than the spawn delay time
if (dt > delay)
{
//Call the SpawnEnemy() function
SpawnEnemy();
//Randomize the spawn delay time, between 2 to 5 seconds
delay = Random.Range (2, 5);
//Initialize the previous spawn time back to the current time
prevSpawnTime = Time.time;
}
}
//Function to spawn new enemies
void SpawnEnemy()
{
//Decrease the SpawnTimer each time one enemy prefab is spawned
SpawnTimer -= 1;
//If 10 enemies are spawned and the number of current enemies spawning each time is less than 5
if (SpawnTimer % 10 == 0 && nEnemies < 5)
{
//Current number of enemies spawning each time +1
nEnemies++;
}
//Clear the List of spawn points
spoints.Clear ();
//Insert a number between 0-4 (the spawn points) starting at 0 into the List of spawn points
spoints.InsertRange (0, new int[]{0,1,2,3,4});
//As long as there are at least one enemy spawning at each time
for (int i = 0; i < nEnemies; i++)
{
//Variable to randomly store the spawn position
int idx = Random.Range(0, spoints.Count-1);
//Initialize the randomly stored spawn position into the List of spawn points
int pos = spoints[idx];
//Remove the randomly stored spawn position from the List so that no other enemy prefabs can spawn from that position
spoints.RemoveAt(idx);
//Instantiate the enemy prefab at the randomly stored spawn position
Instantiate (Enemy, SpawnPoints [pos].position, SpawnPoints [pos].rotation);
}
}
} `
谢谢!
答案 0 :(得分:4)
using System.Random rand;
void Start()
{
rand = new System.Random();
}
public IEnumerator SpawnAtRandTime()
{
while(true)
{
yield return new WaitForSeconds(rand.Next(0,100));
SpawnEnemy();
}
}
这应该可以正常工作。只需在某个循环中使用StartCoroutine(SpawnAtRandTime())
即可。当你想要停止产生敌人时,请调用StopCoroutine()。