简体   繁体   English

实例化一定数量的预制件,统一C#

[英]Instantiate a certain amount of prefabs, unity c#

I wondered how i can instantiate a certain amount of prefabs c#. 我想知道如何实例化一定数量的预制C#。

ex: 例如:

if(Input.GetKeyDown(KeyCode.K))
{
//Instantiate 20 prefabs
}

When the button is pressed, run a loop that loops until the Space value -1 is reached then instantiate a prefab each time in the loop. 当按下按钮时,运行一个循环,直到达到Space-1 ,然后在循环中每次实例化一个预制件。 This should be done in the Update function. 这应该在Update功能中完成。 It shouldn't keep instantiating if you do this correctly. 如果正确执行此操作,则不应继续实例化。

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);
        }
    }
}

I would create a simple method with a single integer parameter, allowing for you to specify how many enemies you would like to create. 我会用一个整数参数创建一个简单的方法,允许您指定要创建多少个敌人。 You are most likely going to need to handle their position with some other logic, unless it is being handled within the inventory slot object itself. 除非在库存广告位对象本身中进行处理,否则您很可能需要使用其他逻辑来处理它们的位置。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM