List prefabs directly under one another in a foreach

Hi, so the functionality I’m trying to get is:

Foreach stock

  1. Grab the info
  2. Instantiate the prefab
  3. Stock count + 1
  4. Repeat but set the space in between the prefab the divider amount.

So for the first stock, it’d be in the starting list place.
The second stock would be -15 under,
The third stock would be -30 under.

The issue is…when it starts, it sets all of the prefabs into one position and moves

Here’s the code

    public void initializeStocks()
    {
        foreach (Stock st in su.stocks)
        {
            var valueEquation = st.price * st.shares;
            var dividerAmount = stockCount * -15;

            // Gets child components of Prefab in order & sets their value to the stock value
            stockObject.transform.GetChild(0).gameObject.GetComponent<Text>().text = st.stockName;
            stockObject.transform.GetChild(1).gameObject.GetComponent<Text>().text = st.price.ToString();
            stockObject.transform.GetChild(2).gameObject.GetComponent<Text>().text = st.changeInPrice.ToString();
            stockObject.transform.GetChild(3).gameObject.GetComponent<Text>().text = st.shares.ToString();
            stockObject.transform.GetChild(4).gameObject.GetComponent<Text>().text = valueEquation.ToString();


            Vector2 newPos = new Vector2(transform.position.x, dividerAmount);
            stockObject.transform.position = newPos;

            Instantiate(stockObject, transform);



            stockCount++;

        }
    }

Hopefully, I explained what’s going on well enough. Not sure what to do as this is the first time I’ve had to create a list like this.

Any help is appreciated :slight_smile:

You are modifying the original prefab (from which all copies inherit values) and then making a copy of it. You should instead make a copy and then modify the copy to look how you want that particular copy to look.

var newStockInstance = Instantiate<TypeOfStockObject>(stockObject, transform);
newStockObject.transform.position = newPos;
newStockObject.transform.GetChild(0).gameObject.GetComponent<Text>().text = st.stockName;
// etc.
1 Like

Works perfectly, thank you for your help.

Jeez…I spent so much time on this & looked for answers everywhere when I could’ve just asked it myself… I would’ve saved hours.

Thanks again.