Моддинг: Базовая обработка инвентаря

From Vintage Story Wiki
This page is a translated version of the page Modding:Basic Inventory Handling and the translation is 100% complete.

Эта страница проверялась в последний раз для версии Vintage Story 1.15.

Other languages:

== Обзор ==

Наиболее важными классами для управления инвентарём являются:

  • InventoryManager: содержит несколько инвентарей (у каждого игрока есть один с разными инвентарями). Также помогает с общими задачами, такими как помещение предметов в действующий инвентарь.
  • IInventory: Представляет инвентарь предметов (например, панель быстрого доступа игроков). Содержит несколько ItemSlots.
  • ItemSlot: Представляет конкретный слот (например, слот для левой руки) инвентаря. Содержит ItemStack слота и методы, помогающие перемещать предметы в этот слот и из него.
  • ItemStack: содержит элемент и количество элементов (называется StackSize), например. «блокировать факел» и StackSize 2 для двух факелов.

Базовая обработка инвентаря

Чтобы получить доступ к инвентарю игроков, вы можете использовать InventoryManager IPlayer. Например, чтобы просто дать игроку факел при возрождении, вы можете использовать TryGiveItemStack:

private ICoreServerAPI serverApi;

public override void StartServerSide(ICoreServerAPI api)
  {
    serverApi = api;
    serverApi.Event.PlayerRespawn += EventOnPlayerRespawn;
  }

private void EventOnPlayerRespawn(IServerPlayer player)
  {
    ItemStack torch = new ItemStack(serverApi.World.GetBlock(new AssetLocation("torch-up")));
    player.InventoryManager.TryGiveItemstack(torch);
  }

If we want to put it directly into the offhand we can use player.Entity.LeftHandItemSlot:

ItemStack torch = new ItemStack(serverApi.World.GetBlock(new AssetLocation("torch-up")));
ItemSlot offhandSlot = player.Entity.LeftHandItemSlot;
if (offhandSlot?.Empty == true)
{
  offhandSlot.Itemstack = torch;
  offhandSlot.MarkDirty(); //this is needed because otherwise the client does not get the update
}

If you need access to other inventories like e.g. the backpack inventories, you can use the InventoryManager.Inventories Property. This contains a dictionary with the name of the inventory (for example "hotbar-APlayerUID") and the corresponding inventory. Another cleaner looking way if you only need a single inventory would be the InventoryManager.GetOwnInventory() method, which appends the player uid to the classname and returns the inventory. To avoid errors when typing the classnames, check first if the classname is already in the GlobalConstants.

Because backpack inventory contains the bags as well as the slots, you have to check if it is valid to put the item there. For this you can use the ItemSlot.CanHold() method.

If for example you want to fill every empty slot in the backpack with single torches you could do the following:

Block torchBlock = _serverApi.World.GetBlock(new AssetLocation("torch-up"));
IInventory backpack = player.InventoryManager.GetOwnInventory(GlobalConstants.backpackInvClassName);
if (backpack != null)
{
  var dummySlot = new ItemSlot(null) { Itemstack = new ItemStack(torchBlock) };
  foreach (ItemSlot bag in backpack.Where(b => b.CanHold(dummySlot) && b.Empty))
  {
    bag.Itemstack = new ItemStack(torchBlock);
    bag.MarkDirty();
  }
}
 

Wondering where some links have gone?
The modding navbox is going through some changes! Check out Navigation Box Updates for more info and help finding specific pages.