自定义的数据排序:比如根据ID排序,或者根据战斗力排序等…
注:本文章源自Unity3D脚本编程。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SortForNeed : MonoBehaviour {
private int heroCount;
private int solderCount;
private List<Hero> HeroeList = new List<Hero>();
void Start () {
HeroeList.Add(new Hero(1, "张一", 100, 100, 200));
HeroeList.Add(new Hero(2, "张二", 600, 200, 100));
HeroeList.Add(new Hero(3, "张三", 300, 300, 200));
HeroeList.Add(new Hero(4, "张四", 400, 400, 400));
HeroeList.Add(new Hero(5, "张五", 150, 500, 100));
HeroeList.Add(new Hero(6, "张六", 500, 200, 200));
this.SortHeros(HeroeList, delegate (Hero obj1, Hero obj2)
{
return obj1.ID.CompareTo(obj2.ID);
}, "按英雄ID排序:");
this.SortHeros(HeroeList, (s, v) =>
{
return s.Atk.CompareTo(v.Atk);
}, "按英雄Atk排序: ");
this.SortHeros(HeroeList, (s, v) =>
{
return s.HP.CompareTo(v.HP);
}, "按英雄HP排序: ");
}
/// <summary>
/// 英雄排序
/// </summary>
private void SortHeros(List<Hero> targets, Comparison<Hero> sortOrder, string orderTitle)
{
Hero[] heros = targets.ToArray();
Array.Sort(heros, sortOrder);
Debug.Log(orderTitle);
foreach (Hero item in heros)
{
Debug.Log("ID:" + item.ID + " HP:" + item.HP + " Atk:" + item.Atk + " Def:" + item.Def);
}
//List<Hero> temp = heros.ToList();
}
}