Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Adding game objects to list small issue.

Discussion in 'Scripting' started by unity_IdF3Y7NrR21HSw, Jun 14, 2018.

  1. unity_IdF3Y7NrR21HSw

    unity_IdF3Y7NrR21HSw

    Joined:
    Apr 3, 2018
    Posts:
    32
    I want to instantiate .. let`s say 100 prefabs and add them to a list of game objects right after each instantiation.
    How can I avoid manually creating a private "Game Object go = Instantiate (prefab, .. );" that so I can add go to the list afterwards, because this way I`d have to create 100 private Game Objects by hand.

    Code (CSharp):
    1. IEnumerator Spawner()
    2.     {
    3.         GameObject go = Instantiate(enemy, transform.position, transform.rotation);
    4.         eney.Add(go);
    5.         yield return new WaitForSeconds(1);
    6.         GameObject go1 = Instantiate(enemy2, transform.position, transform.rotation);
    7.         eney.Add(go1);
    8.         yield return new WaitForSeconds(1);
    9.         GameObject go2 = Instantiate(enemy3, transform.position, transform.rotation);
    10.         eney.Add(go2);
    11.         yield return new WaitForSeconds(1);
    12.     }
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    You do that via a loop

    Code (CSharp):
    1. public int numberToSpawn = 100;
    2.  
    3. IEnumerator Spawner()
    4. {
    5.     for(int i = 0; i < numberToSpawn; i++)
    6.     {
    7.         GameObject go = Instantiate(enemy, transform.position, transform.rotation);
    8.         eney.Add(go);
    9.         yield return new WaitForSeconds(1);
    10.     }
    11. }
     
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,198
    Code (csharp):
    1. //instead of
    2. GameObject go = Instantiate(enemy, transform.position, transform.rotation);
    3. eney.Add(go);
    4.  
    5. //just do:
    6. eney.Add(Instantiate(enemy, transform.position, transform.rotation));
     
  4. unity_IdF3Y7NrR21HSw

    unity_IdF3Y7NrR21HSw

    Joined:
    Apr 3, 2018
    Posts:
    32
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Obviously using a loop is the correct way to do this, but to simply avoid declaring new "go" objects you could have reused the original go object for each instantiation.