You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何用OrderBy对继承类的power属性进行排序?

按子类EquipmentObject的power属性排序的实现方法

要实现按子类的power属性排序,核心是把基类ItemObject安全转换为EquipmentObject后再访问属性,以下是几种实用的实现方式:

情况1:确认所有item都是EquipmentObject类型

如果列表里的物品全是装备类,直接强制转换即可:

sortedItems = new List<GameObject>(allItems.OrderBy(x => ((EquipmentObject)x.GetComponent<InventorySlotItem>().item).power));

注意:如果存在非装备类的ItemObject,这种写法会抛出InvalidCastException异常。

情况2:列表混合普通物品和装备(安全转换)

如果列表里同时有普通物品和装备,用as关键字做安全转换,避免空引用异常,还能给非装备物品设置默认排序值:

sortedItems = new List<GameObject>(allItems.OrderBy(x => {
    var equipment = x.GetComponent<InventorySlotItem>().item as EquipmentObject;
    // 非装备物品按0排序,你可以根据需求改成其他值(比如int.MaxValue把非装备放到最后)
    return equipment?.power ?? 0;
}));

情况3:只筛选装备类再排序

如果只想对装备类物品排序,先通过is关键字过滤,再执行排序:

sortedItems = new List<GameObject>(allItems
    .Where(x => x.GetComponent<InventorySlotItem>().item is EquipmentObject)
    .OrderBy(x => ((EquipmentObject)x.GetComponent<InventorySlotItem>().item).power));

内容的提问来源于stack exchange,提问作者Gleitmehl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:10:34