Unity list.Sort自定义排序

public class PlayInfo
{
    public string name;
    public int power;
    public int type;
    public int brains;

    public PlayInfo(string s,int p,int t,int b)
    {
        name = s;
        power = p;
        type = t;
        brains = b;
    }
    
    /// <summary>
    /// 小于0,放在传入对象的前面,等于0,保持当前的位置不变,大于0,放入传入对象的后面
    /// </summary>
    public static int Compare(PlayInfo p,PlayInfo p1)
    {
        if (p.power > p1.power)
        {
            return -1;
        }
        else if (p.power == p1.power)
        {
            if (p.brains > p1.brains)
            {
                return -1;
            }
            else if(p.brains < p1.brains)
            {
                return 1;
            }
            else
            {
                if (p.type > p1.type)
                {
                    return 1;
                }
                else if(p.type<p1.type)
                {
                    return -1;   
                }
                else
                {
                    return 0;
                }
            }
        }
        else
        {
            return 1;
        }

    }
}


public class playSort : MonoBehaviour
{
    private List<PlayInfo> infos = new List<PlayInfo>();
    private PlayInfo p1 = new PlayInfo("诸葛亮", 30, 5, 100);
    private PlayInfo p2 = new PlayInfo("关羽", 96, 1, 75);
    private PlayInfo p3 = new PlayInfo("吕布", 100, 2, 70);
    private PlayInfo p4 = new PlayInfo("项羽", 100, 2, 72);
    private PlayInfo p5 = new PlayInfo("张良", 30, 4, 100);
    
    // Start is called before the first frame update
    void Start()
    {
       infos.Add(p1);    
       infos.Add(p2);    
       infos.Add(p3);    
       infos.Add(p4);    
       infos.Add(p5);    
       infos.Sort(PlayInfo.Compare);
       foreach (var item in infos)
       {
           Debug.Log(item.name);
       }
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值