For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /server/classes/Container.md.

Class: Container

inventory

Beta

表示一个可以容纳多组物品的容器。用于诸如玩家、运输矿车、羊驼等实体。

Represents a container that can hold sets of items. Used with entities such as Players, Chest Minecarts, Llamas, and more.

Example

containers.ts

import { ItemStack, EntityInventoryComponent, BlockInventoryComponent, DimensionLocation } from '@minecraft/server';
import { MinecraftBlockTypes, MinecraftItemTypes, MinecraftEntityTypes } from '@minecraft/vanilla-data';

function containers(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  const xLocation = targetLocation; // left chest location
  const xPlusTwoLocation = { x: targetLocation.x + 2, y: targetLocation.y, z: targetLocation.z }; // right chest

  const chestCart = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.ChestMinecart, {
    x: targetLocation.x + 4,
    y: targetLocation.y,
    z: targetLocation.z,
  });

  const xChestBlock = targetLocation.dimension.getBlock(xLocation);
  const xPlusTwoChestBlock = targetLocation.dimension.getBlock(xPlusTwoLocation);

  if (!xChestBlock || !xPlusTwoChestBlock) {
    log('Could not retrieve chest blocks.');
    return;
  }

  xChestBlock.setType(MinecraftBlockTypes.Chest);
  xPlusTwoChestBlock.setType(MinecraftBlockTypes.Chest);

  const xPlusTwoChestInventoryComp = xPlusTwoChestBlock.getComponent('inventory') as BlockInventoryComponent;
  const xChestInventoryComponent = xChestBlock.getComponent('inventory') as BlockInventoryComponent;
  const chestCartInventoryComp = chestCart.getComponent('inventory') as EntityInventoryComponent;

  const xPlusTwoChestContainer = xPlusTwoChestInventoryComp.container;
  const xChestContainer = xChestInventoryComponent.container;
  const chestCartContainer = chestCartInventoryComp.container;

  if (!xPlusTwoChestContainer || !xChestContainer || !chestCartContainer) {
    log('Could not retrieve chest containers.');
    return;
  }

  xPlusTwoChestContainer.setItem(0, new ItemStack(MinecraftItemTypes.Apple, 10));
  if (xPlusTwoChestContainer.getItem(0)?.typeId !== MinecraftItemTypes.Apple) {
    log('Expected apple in x+2 container slot index 0', -1);
  }

  xPlusTwoChestContainer.setItem(1, new ItemStack(MinecraftItemTypes.Emerald, 10));
  if (xPlusTwoChestContainer.getItem(1)?.typeId !== MinecraftItemTypes.Emerald) {
    log('Expected emerald in x+2 container slot index 1', -1);
  }

  if (xPlusTwoChestContainer.size !== 27) {
    log('Unexpected size: ' + xPlusTwoChestContainer.size, -1);
  }

  if (xPlusTwoChestContainer.emptySlotsCount !== 25) {
    log('Unexpected emptySlotsCount: ' + xPlusTwoChestContainer.emptySlotsCount, -1);
  }

  xChestContainer.setItem(0, new ItemStack(MinecraftItemTypes.Cake, 10));

  xPlusTwoChestContainer.transferItem(0, chestCartContainer); // transfer the apple from the xPlusTwo chest to a chest cart
  xPlusTwoChestContainer.swapItems(1, 0, xChestContainer); // swap the cake from x and the emerald from xPlusTwo

  if (chestCartContainer.getItem(0)?.typeId !== MinecraftItemTypes.Apple) {
    log('Expected apple in minecraft chest container slot index 0', -1);
  }

  if (xChestContainer.getItem(0)?.typeId === MinecraftItemTypes.Emerald) {
    log('Expected emerald in x container slot index 0', -1);
  }

  if (xPlusTwoChestContainer.getItem(1)?.typeId === MinecraftItemTypes.Cake) {
    log('Expected cake in x+2 container slot index 1', -1);
  }
}

Properties

containerRules?

readonly optional containerRules?: ContainerRules

Beta

Remarks

如果定义了这些规则,其他容器操作如果导致这些规则被违反则会抛出异常。例如,将潜影盒添加到原版 bundles 中。

If these rules are defined other container operations will throw if they cause these rules to be invalidated. For example, adding a shulker box to a vanilla bundle.


emptySlotsCount

readonly emptySlotsCount: number

Beta

Remarks

容器中空槽位的数量。

Count of the slots in the container that are empty.

Throws

如果容器无效则抛出异常。

Throws if the container is invalid.


isValid

readonly isValid: boolean

Beta

Remarks

返回容器对象(或与此容器关联的实体或方块)在此上下文中是否仍然可用。

Returns whether a container object (or the entity or block that this container is associated with) is still available for use in this context.


size

readonly size: number

Beta

Remarks

此容器中的槽位数。例如,一个标准的单方块箱子大小为 27。注意,玩家的物品栏容器共有 36 个槽位,9 个快捷栏槽位加 27 个物品栏槽位。

The number of slots in this container. For example, a standard single-block chest has a size of 27. Note, a player's inventory container contains a total of 36 slots, 9 hotbar slots plus 27 inventory slots.

Throws

如果容器无效则抛出异常。

Throws if the container is invalid.


weight

readonly weight: number

Beta

Remarks

容器中所有物品的总重量。

The combined weight of all items in the container.

Throws

This property can throw when used.

InvalidContainerError

Methods

addItem()

addItem(itemStack): ItemStack | undefined

World Mutation Beta

Parameters

itemStack

ItemStack

要添加的物品堆叠。

The stack of items to add.

Returns

ItemStack | undefined

Remarks

向容器中添加一个物品。该物品将被放置在第一个可用的槽位中,并可以与相同类型的现有物品堆叠。请注意,如果希望在特定槽位中设置物品,请使用 Container.setItem

Adds an item to the container. The item is placed in the first available slot(s) and can be stacked with existing items of the same type. Note, use Container.setItem if you wish to set the item in a particular slot.

Throws

不会因超过重量限制而抛出 ContainerRules 错误,而是会添加物品直至达到重量限制为止。

Won't throw ContainerRules error for over weight limit but will instead add items up to the weight limit.

ContainerRulesError

Error


clearAll()

clearAll(): void

World Mutation Beta

Returns

void

Remarks

清空容器中的所有物品栏物品。

Clears all inventory items in the container.

Throws

如果容器无效则抛出异常。

Throws if the container is invalid.


contains()

contains(itemStack): boolean

Beta

Parameters

itemStack

ItemStack

要查找的物品。

The item to find.

Returns

boolean

Remarks

尝试在容器中查找一个物品。

Attempts to find an item inside the container

Throws

This function can throw errors.

InvalidContainerError


find()

find(itemStack): number | undefined

Beta

Parameters

itemStack

ItemStack

要查找的物品。

The item to find.

Returns

number | undefined

Remarks

查找容器内第一个匹配物品的索引。

Find the index of the first instance of an item inside the container

Throws

This function can throw errors.

InvalidContainerError


findLast()

findLast(itemStack): number | undefined

Beta

Parameters

itemStack

ItemStack

要查找的物品。

The item to find.

Returns

number | undefined

Remarks

查找容器内最后一个匹配物品的索引。

Find the index of the last instance of an item inside the container

Throws

This function can throw errors.

InvalidContainerError


firstEmptySlot()

firstEmptySlot(): number | undefined

Beta

Returns

number | undefined

Remarks

查找容器内第一个空槽位的索引。

Finds the index of the first empty slot inside the container

Throws

This function can throw errors.

InvalidContainerError


firstItem()

firstItem(): number | undefined

Beta

Returns

number | undefined

Remarks

查找容器内第一个物品的索引。

Finds the index of the first item inside the container

Throws

This function can throw errors.

InvalidContainerError


getItem()

getItem(slot): ItemStack | undefined

Beta

Parameters

slot

number

要从中检索物品的槽位的从零开始的索引。最小值:0

Zero-based index of the slot to retrieve items from. Minimum value: 0

Returns

ItemStack | undefined

Remarks

获取指定槽位中的 ItemStack。如果槽位为空,则返回 undefined。此方法不会更改或清空指定槽位的内容。要获取特定槽位的引用,请参阅 Container.getSlot

Gets an ItemStack of the item at the specified slot. If the slot is empty, returns undefined. This method does not change or clear the contents of the specified slot. To get a reference to a particular slot, see Container.getSlot.

Throws

如果容器无效或 slot 索引超出范围则抛出异常。

Throws if the container is invalid or if the slot index is out of bounds.

Example

getFirstHotbarItem.ts

import { world, EntityInventoryComponent, DimensionLocation } from '@minecraft/server';

function getFirstHotbarItem(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  for (const player of world.getAllPlayers()) {
    const inventory = player.getComponent(EntityInventoryComponent.componentId) as EntityInventoryComponent;
    if (inventory && inventory.container) {
      const firstItem = inventory.container.getItem(0);

      if (firstItem) {
        log('First item in hotbar is: ' + firstItem.typeId);
      }

      return inventory.container.getItem(0);
    }
    return undefined;
  }
}

getSlot()

getSlot(slot): ContainerSlot

Beta

Parameters

slot

number

要返回的槽位索引。此索引必须在容器的范围内。最小值:0

The index of the slot to return. This index must be within the bounds of the container. Minimum value: 0

Returns

ContainerSlot

Remarks

返回一个容器槽位。这作为给定索引处槽位的引用。

Returns a container slot. This acts as a reference to a slot at the given index for this container.

Throws

如果容器无效或 slot 索引超出范围则抛出异常。

Throws if the container is invalid or if the slot index is out of bounds.


moveItem()

moveItem(fromSlot, toSlot, toContainer): void

World Mutation Beta

Parameters

fromSlot

number

此容器中要移出物品的从零开始的索引。最小值:0

Zero-based index of the slot to transfer an item from, on this container. Minimum value: 0

toSlot

number

toContainer 中要移入物品的从零开始的索引。最小值:0

Zero-based index of the slot to transfer an item to, on toContainer. Minimum value: 0

toContainer

Container

要移入的目标容器。注意可以是与源容器相同的容器。

Target container to transfer to. Note this can be the same container as the source.

Returns

void

Remarks

将物品从一个槽位移到另一个槽位,可以跨容器移动。

Moves an item from one slot to another, potentially across containers.

Throws

如果此容器或 toContainer 无效,或者 fromSlottoSlot 索引超出范围则抛出异常。

Throws if either this container or toContainer are invalid or if the fromSlot or toSlot indices out of bounds.

ContainerRulesError

Error

Example

moveBetweenContainers.ts

import { world, EntityInventoryComponent, EntityComponentTypes, DimensionLocation } from '@minecraft/server';
import { MinecraftEntityTypes } from '@minecraft/vanilla-data';

function moveBetweenContainers(targetLocation: DimensionLocation) {
  const players = world.getAllPlayers();

  const chestCart = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.ChestMinecart, {
    x: targetLocation.x + 1,
    y: targetLocation.y,
    z: targetLocation.z,
  });

  if (players.length > 0) {
    const fromPlayer = players[0];

    const fromInventory = fromPlayer.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
    const toInventory = chestCart.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;

    if (fromInventory && toInventory && fromInventory.container && toInventory.container) {
      fromInventory.container.moveItem(0, 0, toInventory.container);
    }
  }
}

setItem()

setItem(slot, itemStack?): void

World Mutation Beta

Parameters

slot

number

要放置物品的槽位的从零开始的索引。最小值:0

Zero-based index of the slot to set an item at. Minimum value: 0

itemStack?

ItemStack

要放置在指定槽位中的物品堆叠。将 itemStack 设置为 undefined 将清空该槽位。

Stack of items to place within the specified slot. Setting itemStack to undefined will clear the slot.

Returns

void

Remarks

在特定槽位中设置物品堆叠。

Sets an item stack within a particular slot.

Throws

如果容器无效或 slot 索引超出范围则抛出异常。

Throws if the container is invalid or if the slot index is out of bounds.

ContainerRulesError

Error


swapItems()

swapItems(slot, otherSlot, otherContainer): void

World Mutation Beta

Parameters

slot

number

此容器中要交换的槽位的从零开始的索引。最小值:0

Zero-based index of the slot to swap from this container. Minimum value: 0

otherSlot

number

要交换的槽位的从零开始的索引。最小值:0

Zero-based index of the slot to swap with. Minimum value: 0

otherContainer

Container

要交换的目标容器。注意可以是与源容器相同的容器。

Target container to swap with. Note this can be the same container as this source.

Returns

void

Remarks

在容器内的两个不同槽位之间交换物品。

Swaps items between two different slots within containers.

Throws

如果此容器或 otherContainer 无效,或者 slototherSlot 超出范围则抛出异常。

Throws if either this container or otherContainer are invalid or if the slot or otherSlot are out of bounds.

ContainerRulesError

Error


transferItem()

transferItem(fromSlot, toContainer): ItemStack | undefined

World Mutation Beta

Parameters

fromSlot

number

此容器中要移出物品的从零开始的索引。最小值:0

Zero-based index of the slot to transfer an item from, on this container. Minimum value: 0

toContainer

Container

要移入的目标容器。注意可以是与源容器相同的容器。

Target container to transfer to. Note this can be the same container as the source.

Returns

ItemStack | undefined

包含无法转移的物品的 ItemStack。如果所有物品都已转移,则返回 undefined

An itemStack with the items that couldn't be transferred. Returns undefined if all items were transferred.

Remarks

将物品从一个槽位移到另一个容器,或移到同一容器中的第一个可用槽位。

Moves an item from one slot to another container, or to the first available slot in the same container.

Throws

如果此容器或 toContainer 无效,或者 fromSlottoSlot 索引超出范围则抛出异常。不会因超过重量限制而抛出 ContainerRules 错误,而是会添加物品直至达到重量限制为止。

Throws if either this container or toContainer are invalid or if the fromSlot or toSlot indices out of bounds. Won't throw ContainerRules error for over weight limit but will instead add items up to the weight limit.

ContainerRulesError

Error

Example

transferBetweenContainers.ts

import { world, EntityInventoryComponent, EntityComponentTypes, DimensionLocation } from '@minecraft/server';
import { MinecraftEntityTypes } from '@minecraft/vanilla-data';

function transferBetweenContainers(targetLocation: DimensionLocation) {
  const players = world.getAllPlayers();

  const chestCart = targetLocation.dimension.spawnEntity(MinecraftEntityTypes.ChestMinecart, {
    x: targetLocation.x + 1,
    y: targetLocation.y,
    z: targetLocation.z,
  });

  if (players.length > 0) {
    const fromPlayer = players[0];

    const fromInventory = fromPlayer.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;
    const toInventory = chestCart.getComponent(EntityComponentTypes.Inventory) as EntityInventoryComponent;

    if (fromInventory && toInventory && fromInventory.container && toInventory.container) {
      fromInventory.container.transferItem(0, toInventory.container);
    }
  }
}

同领域相关