Creating a list/array and sorting it (c#)

So I have a game similar to final fantasy which uses turn based combat, I would like to have a script that finds all of the characters in the scene ( there are 18 possible characters divided with player and enemy tags, 9 potential characters on each side) puts them into an array or a list and sorts them by their charSpeed attribute.

This should mean that characters with a higher speed stat get their turn before characters with lower speed stats.

1 How would I go about doing this?

2 should I use a list or an array to store the characters bearing in mind that they can change (for example a character might die or have their speed reduced)?

If any further information or clarity is needed please ask I know I’m asking quite a lot here.

You weren’t very specific about your case. Do you want a single list with all chars or two lists one for players and one for enemies?

However it can be done like this:

// C#
// You need to add this line at the top:
using System.Linq;

// Two seperate lists
var enemies = GameObject.FindGameObjectsWithTag("Enemy").Select(o=>o.GetComponent<YourCharClass>()).ToList();
var players = GameObject.FindGameObjectsWithTag("Player").Select(o => o.GetComponent<YourCharClass>()).ToList();
enemies.Sort((o1, o2) => o1.charSpeed.CompareTo(o2.charSpeed));
players.Sort((o1, o2) => o1.charSpeed.CompareTo(o2.charSpeed));

// or a single list:
var enemies = GameObject.FindGameObjectsWithTag("Enemy").Select(o => o.GetComponent<YourCharClass>());
var players = GameObject.FindGameObjectsWithTag("Player").Select(o => o.GetComponent<YourCharClass>());
var allChars = enemies.Concat(players).ToList();
allChars.Sort((o1, o2) => o1.charSpeed.CompareTo(o2.charSpeed));

Make sure you adjust the tag names to match your tags and replace “YourCharClass” with your char class ^^. If the list is reversed, just replace o1 and o2 inside the lambda expression so it’s sorted the other way round.

The resulting List(s) will contain the YourCharClass references of your chars in the desired order.