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. Dismiss Notice

How To Create An Array of instantiated objects? [Solved!]

Discussion in 'Scripting' started by Avivyouker, Oct 13, 2020.

  1. Avivyouker

    Avivyouker

    Joined:
    Aug 5, 2020
    Posts:
    14
    Im instanstiating Some Random prefabs, and I need to store those prfabs in an array, how could i do that?
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using Random = UnityEngine.Random;
    7.  
    8. public class MasterSpawner : MonoBehaviour
    9. {
    10.     public Image[] Pannels;
    11.     public GameObject[] Plannets;
    12.     GameObject[] PlannetsSave;
    13.     bool UsedOnce = false;
    14.     public void RandomizeAndInstanciate()
    15.     {
    16.         if (!UsedOnce)
    17.         {
    18.             UsedOnce = true;
    19.             foreach (Image i in Pannels)
    20.             {
    21.                 int R = Random.Range(1, Plannets.Length);
    22.                 GameObject GO = Plannets[R];
    23.                 Instantiate(GO, i.transform.position, i.transform.rotation);
    24.  
    25.             }
    26.         }
    27.  
    28.     }
    29.  
    30. }
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Instantiate returns a gameobject. I would just add that to a list rather than an array as it looks like the size would be variable.
     
    PraetorBlue likes this.
  3. Avivyouker

    Avivyouker

    Joined:
    Aug 5, 2020
    Posts:
    14
    oh That Actually could be a way to do it, Il go try it out! thanks!

    edit: Ive messed about with the code and got to this script after some time, Ive added these lines to my codes:
    /// At the top
    public List<GameObject> PlannetsSave = new List<GameObject>();
    /// in the "Foreach" loop.
    GameObject GOB = Instantiate(GO, i.transform.position, i.transform.rotation);
    PlannetsSave.Add(GOB);

    Thanks WarmedxMints!
     
    Last edited: Oct 14, 2020