首页 > 解决方案 > 按字母顺序组织库存

问题描述

所以我创建了一种方法来填充我在 Unity 中创建的库存系统,但是我似乎无法找到按字母顺序排列它们的方法。每个按钮都是作为游戏对象变量按钮持有者面板的子项创建的。每当玩家捡起东西时都会调用此方法。

private void Populate_Inventory ( )
{
    Button btn_CurrentItem;

    int int_Count;

    for ( int_Count = int_PreviousCount; int_Count < strList_Inventory.Count; int_Count++ )
    {
        btn_CurrentItem = Instantiate ( btn_Item, pnl_ButtonHolder.transform );
        btn_CurrentItem.name = strList_Inventory [ int_Count ];
        btn_CurrentItem.GetComponentInChildren<Text> ( ).text = strList_Inventory [ int_Count ];
        btn_CurrentItem.gameObject.AddComponent<Inventory_Item> ( );
        btn_CurrentItem.GetComponent<Inventory_Item> ( ).str_Name = cls_Pickup.str_PickupName;
        btn_CurrentItem.GetComponent<Inventory_Item> ( ).str_Information = cls_Pickup.str_PickupInformation;

        int_PreviousCount = int_Count;
    }

    int_PreviousCount++;
}

如果有人可以提供帮助,将不胜感激。

乔纳森·帕尔默

标签: c#unity3dinventory

解决方案


这种方法的主要问题是,每当您拿起一个项目时,您一次添加单个按钮,并且这些按钮被创建为对象的子pnl_ButtonHolder对象,但您的方法不知道已创建的先前按钮。

选项 1(坏)

添加新按钮后,您可以使用对象GetComponentsInChildren<Button>()上的方法pnl_ButtonHolder获取之前创建的所有按钮组件,然后根据按钮名称对按钮进行排序。

这并不理想,因为GetComponentsInChildren<>()它是一种昂贵的方法,并且不能很好地利用库存的概念。

选项 2(好)

创建一个Inventory类来管理您的实际库存,包括分类项目。它可能看起来像这样:

public class Inventory_Button : MonoBehaviour
{
    public Button button = default;

    public void Initialize(Intenvory_Item item)
    {
        button.name = item.name;
        // Other work here.
    }
}

public class Inventory : MonoBehaviour
{
    public GameObject inventoryItemPrefab = default;
    public Transform inventoryParent = default;

    private List<Inventory_Item> _inventory = new List<Inventory_Item>();
    private List<Inventory_Button> _inventoryButtons = new List<Inventory_Button>();

    public void AddItem(Intenvory_Item item)
    {
        _inventory.Add(item);
        Inventory_Button button = GameObject.Instantiate(inventoryItemPrefab, inventoryParent).GetComponent<Inventory_Button>();
        button.Initialize(item);
        _inventoryButtons.Add(button);
        _inventoryButtons.Sort((x, y) => x.name.CompareTo(y.name));
    }

    public void RemoveItem(Inventory_Item item)
    {
        // Do work to remove the item.
    }
}

出于以下几个原因,这种设置很有用:

  1. 您的库存管理现在由单个类而不是对象集合处理。这使它易于交互。
  2. 这将使将来删除项目变得更加容易。在您当前的实施中,您似乎很难从玩家的库存中移除物品。
  3. Inventory它将一个类、一个Inventory_Item类和一个类之间的职责分开Inventory_Button,每个类都独立存在并一起工作。

最后的几点说明:

  • 我在上面的两个类中遗漏了一些细节。您应该填写它们以适应您的游戏需求。
  • 通过使用类似Insertion Sort的方法,您可以更有效地进行排序。此解决方案将完成工作。
  • 使用前缀来命名变量可能会让试图阅读代码的人感到困惑。我建议您查看样式指南。这里有一个很棒的。

推荐阅读