[C#] Sorting a List of Gameobjects Alphabetically

i have this code, it find all gameobjects that are marked as a waypoint and adds it to a list/array.

using UnityEngine;
using System.Collections;

public class CreepAI : MonoBehaviour {
	//Vars
	public GameObject Target = null;
	public GameObject[] WayPoints;
	void Awake () {
		FindWayPoints();
	}
	void FindWayPoints()
	{
		WayPoints = GameObject.FindGameObjectsWithTag("Waypoint");
		
	}
	void LateUpdate () {
		if(Target = null)
			Target = FindClosestEnemy();
		FindWayPoints();
	}
 	
}

When i run the code the gameobjects are arranged in a way that makes no sense, they are not arranged in the world this way or in the hierarchy this way.

1372-Untitled.png

i want to be able to sort this list, so Wp0 will be first and Wp7 will be last in order.

Try (tested and approved) :

using System.Linq;

// …

void FindWayPoints()
{
   WayPoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy( go => go.name ).ToArray();
}

After you grab all of the waypoints in FindWayPoints(), sort the WayPoints array by the waypoint’s gameobject name.

Just to get you going, you can use Array.Sort – check out MSDN

Try something like:

Array.Sort(WayPoints, delegate(GameObject wp1, GameObject wp2) { return wp1.name.CompareTo(wp2.name); });

(I didn’t test that - no guarantees on that compiling!)

However, Array.Sort and GameObject.FindGameObjectsWithTag are both very slow. Probably not something you want to be doing everytime you create a new NPC. I’d recommend considering switching over to creating a gameobject named something like “WaypointRegistry” that also has a “WaypointRegistry” script that implements a singleton – that script would do the work once to maintain your sorted list of waypoints in the scene, and then provide static and centralized access to this list. Your creeps could simply call something like “Waypoints = WaypointRegistry.GetAllWaypoints();”

It also looks like you have a bug in your LateUpdate(), you probably meant to write “if(Target == null)” instead of assigning Target = null.

Hope this helped!