Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. 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.

  1. unity_IdF3Y7NrR21HSw

    unity_IdF3Y7NrR21HSw

    Joined:
    Apr 3, 2018
    Posts:
    31
    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,076
    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,347
    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:
    31
  5. Joe-Censored

    Joe-Censored

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