- Home /
Order a GameObject Array
i want to order a GameObject Array called with the GameObject.FindObjectsWithTag
i'm using this part of script:
itemsCount = items.Length;
itemsIdentity = new int[itemsCount];
for (int i = 1; i <= itemsCount; i++)
{
foreach (GameObject item in items)
{
itemScript = item.GetComponent <ItemData> ();
if (itemScript.ID == i)
{
items.SetValue (item, itemScript.ID - 1);
itemsIdentity [itemScript.ID - 1] = itemScript.ID;
}
}
}
i don't understand why, but with the item.SetValue (item, itemScript.ID - 1); line, in the Array will be only one of these GameObject.
any advice?
Do you actually need them to be sorted or just need to reference them by ID? You could use a Dictionary < int, GameObject >
Answer by RavenOfCode · May 28, 2016 at 04:21 AM
Take out the for loop its causing your itemScript.ID to get messed up (ie. the last run of the foreach loop they will all have the same ID.
I understand the problem: if i set a different value of the array during the foreach loop, this one doesn't read the object who changed the value, so i get only one object for all the array.
Now the question is another one: how can I order my Array?
Sorry for the late response, I didn't get a notification.
Try using lists ins$$anonymous$$d.
Something like this:
public int size; //the size you want the list to be
private List<GameObject> items; //default size is 0
void Start ()
{
int amount;
while (amount < size) //keeps searching while items isn't full
{
items.Insert(amount, GameObject.FindGameObjectsWithTag("items")[amount]); //adds an item from FindGameObjectsWithTag to items
amount++; //increases amount towards size
}
}