我想知道如何实例化一定数量的预制C#。
例如:
if(Input.GetKeyDown(KeyCode.K))
{
//Instantiate 20 prefabs
}
答案 0 :(得分:4)
按下按钮时,运行一个循环,直到达到Space
值-1
,然后在每次循环中实例化一个预制件。这应该在Update
函数中完成。如果操作正确,它不应该继续实例化。
int Space = 20;
public GameObject prefab;
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
//Instantiate 20 prefabs
for (int i = 0; i < Space; i++)
{
GameObject obj = Instantiate(prefab);
obj.transform.position = new Vector3(0, 0, 0);
}
}
}
答案 1 :(得分:1)
我会用一个整数参数创建一个简单的方法,允许您指定要创建多少个敌人。除非在库存广告位对象本身中进行处理,否则您很可能需要使用其他逻辑来处理它们的位置。
public GameObject enemyPrefab;
//runs every frame, to check for the key press in this case
public void Update ()
{
//did we press the specified key? (C)
if (Input.GetKeyDown(KeyCode.C))
{
//call our method to create our enemies!
CreateEnemies(20);
}
}
public void CreateEnemies (int enemies)
{
//the amount of enemies we want to have
//run through this loop until we hit the amount of enemies we want
for (int i = 0; i < enemies; i++)
{
//create the new enemy based on the provided prefab
Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity);
}
}