User Tools

Site Tools


zh_cn:tutorial:items

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
zh_cn:tutorial:items [2024/10/27 14:37] solidblockzh_cn:tutorial:items [2024/12/08 14:24] (current) – [创建物品实例] solidblock
Line 6: Line 6:
 ===== 创建物品实例 ===== ===== 创建物品实例 =====
 :!: 如果是使用的 1.21.2 之后的版本,请直接跳到[[#在 1.21.2+ 中创建物品]]。 :!: 如果是使用的 1.21.2 之后的版本,请直接跳到[[#在 1.21.2+ 中创建物品]]。
 +
 首先,创建 ''Item'' 的实例,存储为静态常量字段。''Item'' 的构造方法接受一个 ''Item.Settings''(或 ''FabricItemSettings'',除非是 1.20.5 以上版本)对象,该对象用于设置物品属性,例如耐久和堆叠数量。为了简便,就直接在 ''ExampleMod'' 中做了,然后存为静态字段。 首先,创建 ''Item'' 的实例,存储为静态常量字段。''Item'' 的构造方法接受一个 ''Item.Settings''(或 ''FabricItemSettings'',除非是 1.20.5 以上版本)对象,该对象用于设置物品属性,例如耐久和堆叠数量。为了简便,就直接在 ''ExampleMod'' 中做了,然后存为静态字段。
  
Line 185: Line 186:
 如果你正确执行了所有操作,则使用该物品现在应该会播放声音。 如果你正确执行了所有操作,则使用该物品现在应该会播放声音。
  
-===== 如果我更改物品的堆叠大小怎么办? =====+===== 物品组件 ===== 
 +有时你会物品添加一些默认物品组件,例如最大堆叠数量或防火。可以通过调用 ''Item.Settings'' 的 ''component'' 方法来完成。关于物品组件的详细教程,可见 [[https://docs.fabricmc.net/zh_cn/develop/items/custom-data-components|Fabric Docs 上的教程]]。 
 + 
 +这个例子中,物品默认不可破坏,并隐藏关于这一点的物品提示: 
 +<yarncode java> 
 +    // For versions below 1.21.2: 
 +    public static final CustomItem CUSTOM_ITEM register("custom_item", new CustomItem(new class_1792.class_1793() 
 +        .component(DataComponentTypes.UNBREAKABLE, new UnbreakableComponent(true)))); 
 +    // For versions since 1.21.2: 
 +    public static final Item CUSTOM_ITEM register("custom_item", CustomItem::new, new Item.Settings() 
 +        .component(DataComponentTypes.UNBREAKABLE, new UnbreakableComponent(true))); 
 +</yarncode> 
 + 
 +特别地,最大堆叠数可使用 ''Item.Settings'' 内的 ''maxCount(int size)'' 方法(在 1.20.5 之前也有效)来指定。请注意,如果你的物品是有耐久的,那么无法设置最大堆叠数,否则游戏将抛出 ''RuntimeException''
  
-使用 ''Item.Settings'' 内的 ''maxCount(int size)'' 来指定最大堆叠数。请注意,如果你的物品是有耐久的(及耐久归零后会被破坏),那么此物品无法设置最大堆叠数,否则游戏将抛出 RuntimeException。 
 <yarncode java [enable_line_numbers="true"]> <yarncode java [enable_line_numbers="true"]>
 public class ExampleMod implements ModInitializer { public class ExampleMod implements ModInitializer {
- +    // 我们新物品的实例,最大堆叠为 16 
-    // 我们新物品的实例,最大堆叠大小为16 +     
-    public static final CustomItem CUSTOM_ITEM = new CustomItem(new class_1792.class_1793().maxCount(16));+    // For versions below 1.21.2: 
 +    public static final CustomItem CUSTOM_ITEM = register("custom_item", new CustomItem(new class_1792.class_1793().maxCount(16))); 
 +    // For versions since 1.21.2: 
 +    public static final Item CUSTOM_ITEM = register("custom_item", CustomItem::new, new Item.Settings().maxCount(16));
     [...]     [...]
 } }
 </yarncode> </yarncode>
 +
  
 ===== 让物品能作为燃料或者可堆肥 ===== ===== 让物品能作为燃料或者可堆肥 =====
zh_cn/tutorial/items.1730039869.txt.gz · Last modified: 2024/10/27 14:37 by solidblock