c# - 如何统一从数组中仅实例化一个对象
问题描述
我想一次只实例化一个对象,所以我不知道我的代码有什么问题,因为它同时实例化了数组中的所有对象。使用随机范围是可能的,但我想按顺序将其实例化。
void Update()
{
if (timer > maxTime)
{
// Shuffle(enemies);
// RandomNumber = Random.Range(0, enemies.Length);
float center = Screen.width / Screen.height;
CreateEnemies(center);
// newEnemie = Instantiate(enemies[RandomNumber]);
// newEnemie.transform.position = transform.position+new Vector3(Random.Range(-screenBounds.x -1.5f, screenBounds.x +1.5f), 0, 0);
// newEnemie.transform.position = transform.position + new Vector3(Random.Range(-screenBounds.x + 1.5f, screenBounds.x - 1.5f), 0, 0);
timer = 0;
}
timer += Time.deltaTime;
}
void Shuffle(GameObject[] array)
{
for (int i = 0; i < array.Length; i++)
{
GameObject temp = array[i];
int random = Random.Range(i, array.Length);
array[i] = array[random];
array[random] = temp;
}
}
void CreateEnemies(float positionY)
{
for(int i = 0; i < enemies.Length; i++)
{
enemies[i] = Instantiate(enemies[i], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity)as GameObject;
positionY += 1f;
}
}
解决方案
您的 create Enemies 函数执行所说的,它实例化敌人(复数)。当函数被调用时,它会遍历整个数组并实例化所有敌人。如果每次调用函数时只想要 1 ,则可以使用类似的东西。
private int currentEnemyIndex = 0;//Enemy to spwan index
void CreateEnemies(float positionY)
{
if (currentEnemyIndex < enemies.Length)//Make sure you don't go out of bound for your array. You could also clamp if you want to keep spwaning the last one.
{
enemies[currentEnemyIndex] = Instantiate(enemies[currentEnemyIndex], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity) as GameObject;
positionY += 1f;
++currentEnemyIndex;//Increment the enemy index so next call you spwan the next enemy.
}
}
推荐阅读
- logic - 如何在 clgo 中实现关键约束?
- visual-studio - 将 Visual Studio 转换为 gradle
- javascript - React/JavaScript 中的箭头函数
- class - Cython:我可以使用 cppclass 代替 class 吗?它有什么性能优势吗?
- reactjs - Django + React 多少请求太多了?
- c# - prestashop 将类别树重新生成到 c#
- parrot-os - Parrot OS 卡住了
- vue.js - 服务工作者缓存与 VuexPersistence
- node.js - 反应表 - 多个值到单元格
- sql - Oracle SQL 空行顺序