这篇主要说的是unity对list中的gameObject排序问题,现在我们具体来看。
首先定义一个List类,这个类里面包含了Name和Total两个属性变量,下面就是针对这两个变量进行排序。
  1. public class Player
  2. {
  3. public string Name { get; set; }
  4. public int Total { get; set; }
  5. public Player(string name, int total)
  6. {
  7. Name = name;
  8. Total = total;
  9. }
  10. }

然后我们创建一个List,这个List是Player对象的一个List集,创建好List后,需要为List添加一些节点,下面添加了6条数据。

  1. List<Player> lst = new List<player>();
  2. lst.Add(new Player("John", 100));
  3. lst.Add(new Player("Smith", 120));
  4. lst.Add(new Player("Cait", 97));
  5. lst.Add(new Player("Irene", 100));
  6. lst.Add(new Player("Ben", 100));
  7. lst.Add(new Player("Deniel", 88));

我们通过List.Sort() 方法来进行排序

1:通过Total变量来进行升序排序
  1. lst.Sort(delegate(Player x, Player y)
  2. {
  3. return x.Total.CompareTo(y.Total);
  4. });
2:通过Total进行降序排序
  1. lst.Sort(delegate(Player x, Player y)
  2. {
  3. return y.Total.CompareTo(x.Total);
  4. });
3:通过多个元素进行排序
  1. lst.Sort(delegate(Player x, Player y)
  2. {
  3. // Sort by total in descending order
  4. int a = y.Total.CompareTo(x.Total);
  5. // Both player has the same total.
  6. // Sort by name in ascending order
  7. if (a == 0)
  8. a = x.Name.CompareTo(y.Name);
  9. return a;
  10. });
4:通过Linq进行排序
  1. var result1 = lst.OrderBy(a => a.Total);
  2. var result3 = lst.OrderBy(a => a.Total).ThenBy(a => a.Name);
  3. var result2 = lst.OrderByDescending(a => a.Total).ThenByDescending(a => a.Name);