Problem with instantiating in a for loop from a list

The code below is what I am using to generate my shop items at runtime.

Code

    private void InitializeStore ()
    {
        for (int i = 0; i < storeItems.Count; i++)
        {
            //Create an empty slot
            var slotInstance = Instantiate (storeSlot);
            slotInstance.transform.SetParent (storeSlotParent.transform);

            //Create an empty image in this slot
            var iconInstance = Instantiate (itemImage);
            itemImage.GetComponent<Image> ().sprite = storeItems[i].itemIcon;
            iconInstance.transform.SetParent (slotInstance.transform, false);

            //Create a buy button in this slot
            var buttonInstance = Instantiate (buyButton);
            buttonInstance.transform.SetParent (slotInstance.transform, false);
            //Assign itemID to buttonID
            int tempID = storeItems [i].itemID;
            buttonInstance.GetComponent<StoreBuyButton> ().SetID (tempID);
        }
    }

I’m not sure why but the different IDs won’t match up (buttonID will not always match with the correct iconID), and sometimes the first item shows the wrong icon. This error is strange because sometimes the right item will spawn, sometimes not. Also, the last item in my list seems to be the first one that gets instantiated. Why is this?

I thought that each one of these items would be created before it iterated to the next item in the list, so why am I having these mismatch issues?

Any help would me kindly appreciated!

EDIT:

I’m 99% sure it is because the last item is instantiating first that I am getting the issue of the ID’s not matching up. The instantiated buttons actually have the correct ID’s (correct order I mean) but the reason they don’t match up is because the last item in the lists icon instantiates first which has a ripple effect.

You are Instantiate(itemImage) and assigning it to iconInstance.
But then right after, you are doing GetComponent on the itemImage. If this is a prefab, you’re actually changing the prefab. Did you mean to GetComponent on the iconInstance?

Wow. Not tried but I imagine that is definitely the issue. Always the simple things with me it would explain the imakes being out by one anyway! Cheers Brathnann!