开发教程

ScriptAPI自定义组件教程

已注销***禁止访问 发表于 2024-8-21 · 最后回复 2024-11-20 IP:安徽省 3,585 2
阅读该教程需要一定的JavaScript基础,若没有请退出,谢谢。
教程禁止水评论,若对你有用请回复一个“有用”。

教程开始。
官方教程:
TypeScript
  1. import { ItemComponentConsumeEvent, world } from "@minecraft/server";

  2. world.beforeEvents.worldInitialize.subscribe(initEvent => {
  3.   initEvent.itemComponentRegistry.registerCustomComponent('example:add_night_vision_on_consume', {
  4.     onConsume(arg: ItemComponentConsumeEvent) {
  5.       arg.source.addEffect('minecraft:night_vision', 600);
  6.     }
  7.   });
  8. });
复制代码


1.导入必要模块
JavaScript:
  1. import { ItemComponentConsumeEvent, world } from "@minecraft/server";
复制代码


2.监听 worldInitialize 事件
JavaScript
  1. world.beforeEvents.worldInitialize.subscribe((initEvent) => {
  2.   // 这里将添加自定义组件的代码
  3. });
复制代码


3.注册自定义物品组件
说明:在 worldInitialize 事件的处理函数中,我们可以使用 itemComponentRegistry 来注册自定义组件。
  1. initEvent.itemComponentRegistry.registerCustomComponent('example:add_night_vision_on_consume', {
  2.   onConsume(arg) {
  3.     arg.source.addEffect('minecraft:night_vision', 600);
  4.   }
  5. });
复制代码

其他说明:arg返回的是ItemComponentConsumeEvent 类
链接:ItemComponentConsumeEvent

创建完成后在JSON中的components对象中写入以下代码
  1. "minecraft:custom_components": [
  2.     "example:add_night_vision_on_consume"
  3. ]
复制代码

4.实现功能
  1. world.beforeEvents.worldInitialize.subscribe((initEvent) => {
  2.   initEvent.itemComponentRegistry.registerCustomComponent('example:add_night_vision_on_consume', {
  3.     onConsume: (arg) => {
  4.       arg.source.addEffect('minecraft:night_vision', 600);//实现夜视药水效果
  5.     }
  6.   });
  7. });
复制代码

说明:
onConsume为物品被吃掉后调用
详细页ItemCustomComponent Interface
回复 2 最早 最新 只看楼主
已注销*** 楼主禁止访问
2024-11-20 09:34:49 · 来自手机 IP:浙江省

  1. import { world, system } from "@minecraft/server";

  2. world.beforeEvents.worldInitialize.subscribe((event) => {
  3.     event.itemComponentRegistry.registerCustomComponent("<自定义组件的标识符>", {
  4.         onUse(E) {
  5.             system.runJob(Tigger(E.source))
  6.         }
  7.     })
  8. })

  9. function* Tigger(player) {
  10.     player.addEffect("night_vision",100,{amplifier:255,showParticles:false})
  11.     yield;
  12. }
复制代码
3# 2024-11-20 09:34:49 回复 收起回复
您需要登录后才可以回帖 登录 | 立即注册
本版积分规则