Search Unity

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,334
    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.