Search code examples
c#unity-game-engineinstantiation

Instantiate a certain amount of prefabs, unity c#


I wondered how i can instantiate a certain amount of prefabs c#.

ex:

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

Solution

  • 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. This should be done in the Update function. 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);
            }
        }
    }