Search Unity

  1. Unity 2018.1 has arrived! Read about it here
    Dismiss Notice
  2. Scriptable Render Pipeline improvements, Texture Mipmap Streaming, and more! Check out what we have in store for you in the 2018.2 Beta.
    Dismiss Notice
  3. If you couldn't join the live stream, take a peek at what you missed.
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Learn more.
    Dismiss Notice
  5. ARCore is out of developer preview! Read about it here.
    Dismiss Notice
  6. Magic Leap’s Lumin SDK Technical Preview for Unity lets you get started creating content for Magic Leap One™. Find more information on our blog!
    Dismiss Notice
  7. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Adding game objects to list small issue.

Discussion in 'Scripting' started by unity_IdF3Y7NrR21HSw, Jun 14, 2018 at 1:56 PM.

  1. unity_IdF3Y7NrR21HSw

    unity_IdF3Y7NrR21HSw

    Joined:
    Apr 3, 2018
    Posts:
    24
    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:
    987
    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:
    3,022
  4. unity_IdF3Y7NrR21HSw

    unity_IdF3Y7NrR21HSw

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

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    2,547
    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.