Sorting a list of GameObjects by accessing their int values

I have the following code where I make a list of all the GameObjects in the scene with the tag ‘Character’. What I want to do is to sort the list based on the int initiative that every Character in the scene has. The initative of every character can be found in the script CharacterStats. How do I make it Sort the list correctly and once it hits the lowest variable it will refresh the list and start over again from the highest value.

public class TurnBasedStates : MonoBehaviour {

public List<GameObject> characterList = new List<GameObject>(); 

void Start () {
	GameObject[] allCharacters = GameObject.FindGameObjectsWithTag ("Character");
		foreach (GameObject character in allCharacters) 
	{
		characterList.Add (character);

	}
}

public class CharacterStats : MonoBehaviour {

public int initiative = 40;
public bool isActive = false;
public Camera cameras;

// Use this for initialization
void Start () {
	//cameras = Transform.FindObjectOfType<Camera> ();
	//cameras = Transform.FindObjectOfType<Camera> ();
	cameras = gameObject.GetComponentInChildren<Camera> ();
}

// Update is called once per frame
void Update () {
	if (isActive) {
		cameras.enabled = true;
	} 
	else {
		cameras.enabled = false;
	}
}

}

I write simple sort for your case:

 public List<GameObject> characterList = new List<GameObject>(); 

 void Start () {
  GameObject[] allCharacters = GameObject.FindGameObjectsWithTag("Character");
  foreach (GameObject character in allCharacters) {
   characterList.Add (character);
  }
  //Sorting list and check it count
  if (characterList.Count > 0) {
   characterList.Sort(delegate(GameObject a, GameObject b) {
    return (a.GetComponent<CharacterStats>().initiative).CompareTo(b.GetComponent<CharacterStats>().initiative);
   });
  }
 }

I hope that it will help you.

P.S.: For sort object in your case applied OrderBy() from System.Linq too. Simple change sort on:

 characterList = characterList.OrderBy(x=>x.GetComponent<CharacterStats>().initiative).ToList();

Try This:

void Start() {
		GameObject[] allCharacters = GameObject.FindGameObjectsWithTag("Character");
		foreach (GameObject character in allCharacters) {
			characterList.Add(character);
		}
		characterList.Sort((IComparer<GameObject>)new sort());
	}

	private class sort : IComparer<GameObject>{
		int IComparer<GameObject>.Compare(GameObject _objA, GameObject _objB) {
			int t1 = _objA.GetComponent<CharacterStats>().initiative;
			int t2 = _objB.GetComponent<CharacterStats>().initiative;
			return t1.CompareTo(t2);
		}
	}