- Home /
Sorting an array of GameObjects based on its name.
I'm making a 2d board game for which I want to implement player movement along tiles based on a dice roll. The problem is when I create an array for the tiles, it's stored in a random order. For eg: the debug log of tiles[0] returns gameobject tile 12 instead of gameobject tile0. How do I sort this array so that I get tiles[0] returns tile0, tiles[1] returns tile1.....etc.
using UnityEngine;
using System.Collections;
public class Tiles : MonoBehaviour {
//GameObject Alltiles is a parent of other gameobjects such as tile1,tile2,tile3....tile23.
public GameObject Alltiles;
//creating an array named tiles to store all other tile gameobjects.
public GameObject[] tiles;
// Use this for initialization
void Start () {
tiles = GameObject.FindGameObjectsWithTag("tile");
System.Array.Sort(tiles);
Debug.Log(tiles[0]);
Debug.Log(tiles[1]);
Debug.Log(tiles[2]);
Debug.Log(tiles[3]);
Debug.Log(tiles[4]);
Debug.Log(tiles[5]);
}
// Update is called once per frame
void Update () {
}
}
You could retrieve the objects name with GameObject[0].name then use the string compare method. http://msdn.microsoft.com/en-us/library/84787k22(v=vs.110).aspx Then depending on the value returned you would swap array elements!
Answer by stormcloak · Jan 10, 2015 at 03:44 AM
The above two answers didn;t work but the one from this thread worked perfectly fine! http://forum.unity3d.com/threads/c-array-sorting-horror-solved.24077/
Answer by thegreatzebadiah · Jan 08, 2015 at 07:38 AM
I would use a sorted dictionary. Just insert each object with the name as the key like this:
SortedDictionary<string, GameObject> sortedTiles = new SortedDictionary<string, GameObject>();
for (int i = 0; i < tiles.Length; i++)
{
sortedTiles.Add(tiles[i].name, tiles[i]);
}
then to iterate through in sorted order you could:
foreach(KeyValuePair<string, GameObject> tile in sortedTiles)
{
// Do something with tile
}
or if you want to get back to an array and have convenient index access:
tiles = sortedTiles.Values.ToArray();
Answer by Mangas · Jan 08, 2015 at 07:37 AM
Perhaps it's easier to just set up the array in the correct order rather than initializing it, assigning all gameobjects and then sorting it.
If your gameobjects are named as tile0, tile1, tile2... etc. Try to make a loop where you assign each tile like this:
tiles[i] = GameObject.FindGameObjectsWithTag("tile" + i)
Your answer
![](https://koobas.hobune.stream/wayback/20220613175853im_/https://answers.unity.com/themes/thub/images/avi.jpg)