So, for my game, I’m making a shop system where shop objects in an array are assigned to different locations (transforms) in an array for display. I’m not sure how to do this but here is my failed attempt:
public float itemNumber;
public GameObject[] shopItems;
public GameObject[] current;
public Transform[] shopSpots;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
foreach (Transform transform in shopSpots)
{
foreach(GameObject gameObject in shopItems)
{
Transform j = gameObject.GetComponent<Transform>();
j = transform;
}
}
}
First, when you put one loop inside of another, you run through the entire inner loop once for each thing in the outer loop. This gives you the cartesian product of the collections; that is, every possible pairing.
What you want instead is a single loop that goes through both collections in parallel. You can do that with something like this:
for (int i = 0; i < Mathf.Min(shopItems.Length, shopSpots.length); ++i)
{
GameObject currentItem = shopItems[i];
Transform currentShopSpot = shopSpots[i];
// Do stuff using currentItem and currentShopSpot
}
The reason for Mathf.Min() is to stop as soon as you reach the end of either array, because you’d get an error if you tried to read stuff past the end of the array. You might also need to do something for “leftover” slots and/or items if the arrays are not the same length.
Your second problem is that the thing you’re trying to do with the transforms doesn’t really make sense. You can’t change the item’s transform to BE some other transform; Unity doesn’t work like that. Every game object already has its own transform; two objects can’t share the same transform.
But here are some things you might want to do instead:
You could move the item to the location of the slot. To do that, you’d say: currentItem.transform.position = currentShopSpot.position;
You could make the item be a child of the slot in the hierarchy. To do that, you’d say: currentItem.transform.SetParent(currentShopSpot);
This could be useful if you wanted the item to automatically move/rotate when the shop moves/rotates, or if these are UI objects and you want to take advantage of some of Unity’s automatic layout functionality, or if you need mouse-clicks on the item to be handled by the slot.