This is an old revision of the document!
Table of Contents
监听事件
在本教程中,你会学到:
- 理解事件和回调
- 对已有的事件注册回调
事件
事件是用存储并调用回调的 net.fabricmc.fabric.api.event.Event
的实例代表的,通常回调有单个事件实例,存储在回调接口的 EVENT
静态字段中,但也有其他的形式。例如,ClientTickEvents 将几个有关的事件分组在一起。
回调
每个事件都有对应的回调接口,通常命名为 EventNameCallback
。回调是通过在事件接口调用 register()
来注册的,调用时需要一个回调接口实例作为参数。
Fabric API 中的回调接口
All event callback interfaces provided by Fabric API can be found in the net.fabricmc.fabric.api.event
package.
A partial list of existing callbacks is provided at the bottom of this tutorial.
自定义回调
Although there are plenty of events already provided by Fabric API, you can still make your own events. Please refer to events.
实例
This example registers an AttackBlockCallback
to damage players when they hit blocks that don't drop when hand-mined. It returns ActionResult.PASS
as other callbacks should still be called. See the AttackBlockCallback JavaDoc in your IDE for the meaning of other values.
public class ExampleMod implements ModInitializer { [...] @Override public void onInitialize() { AttackBlockCallback.EVENT.register((player, world, hand, pos, direction) -> { BlockState state = world.getBlockState(pos); /* Manual spectator check is necessary because AttackBlockCallbacks fire before the spectator check */ if (state.isToolRequired() && !player.isSpectator() && player.getMainHandStack().isEmpty()) { player.damage(DamageSource.field_5869, 1.0F); } return ActionResult.PASS; }); } }
Fabric API 事件
玩家交互事件
玩家:AttackBlockCallback / AttackEntityCallback / UseBlockCallback / UseEntityCallback / UseItemCallback
玩家(客户端):ClientPickBlockApplyCallback / ClientPickBlockCallback / ClientPickBlockGatherCallback
注册表事件
BlockConstructedCallback / ItemConstructedCallback
RegistryEntryAddedCallback / RegistryEntryRemovedCallback / RegistryIdRemapCallback
战利品事件
关于使用 LootTableLoadingCallback
的例子,请参考此教程。