Hey all,
I want to load GameObjects in an array with the following code. The problem is that the array is loaded in reversed order, so the first gamobject in de hierarchy is the last one in the array. Is there a way to change this??
public GameObject[] trackPoints;
public float distanceToNextTrackPoint;
public int currentTrackPoint = 0;
void Start ()
{
//If points can be found, calculate distance to first point
trackPoints = GameObject.FindGameObjectsWithTag("TrackPoint");
if(trackPoints != null)
{
distanceToNextTrackPoint = Vector3.Distance(transform.position, trackPoints[currentTrackPoint].transform.position);
}
You shouldn’t have any expectations about the order of Objects returned by GameObject.FindGameObjectsWithTag(“TrackPoint”). That is completely beyond your control.
If you want them ordered a certain way, you’ll need to sort them after you retrieve them.
After getting your objects you can sort them according to their names, like:
Array.Sort(trackPoints , (x, y) => x.name.CompareTo(y.name));
Or if you have more complex sorting logic then you can create your own IComparer class:
/// <summary>
/// Object sorter optimized to use like this:
/// Object_1
/// Object_2
/// Object_3
/// Object_4
/// </summary>
public class ObjectSorter : IComparer
{
int IComparer.Compare(object x, object y)
{
string xName = ((GameObject)x).name;
string yName = ((GameObject)y).name;
if (xName.Contains("_") && yName.Contains("_"))
{
int a = int.Parse(xName.Split('_')[1]);
int b = int.Parse(yName.Split('_')[1]);
return a - b;
}
else
{
// Format error but we sort it to the name anyway
return xName.CompareTo(yName);
}
}
}
And use it like this:
// This goes to your definitions field
private IComparer mObjectSorter = new ObjectSorter();
..
..
// In your method
Array.Sort(mObjects, trackPoints);
Ive encountered a similar problem and could find a solution or understanding of the sorting in ther array.
initially i worked with a predifined name for the track points along with an incremented id
ex: Point_0, Point_1, Point_2, Point_3,...
and then interate throung the Containing GameObject
for (int i = 0; i < wayPointContainer.childCount; i++){
GameObject wayPointGO = wayPintContainer.Find( "Point" + (i) );
wayPointArray.push (wayPointGO);
}
but generally both solutions are a bit of a hassle to maintain…
So i ended up Using the poly line editor Script witch is a very simple editor tool that allow you to create path and get it back as a Vector3 Array.
http://wiki.unity3d.com/index.php/PolyLineEditor
the source is a been out of date so also look at this
http://answers.unity3d.com/questions/330120/polyline-script-form-unify-wiki-help.html