User Tools

Site Tools


zh_cn:tutorial:callbacks

This is an old revision of the document!


map2fabricyarn - Page contains unknown Intermediary names:
field_5869

监听事件

在本教程中,你会学到:

  1. 理解事件和回调
  2. 对已有的事件注册回调

事件

事件是用存储并调用回调的 net.fabricmc.fabric.api.event.Event 的实例代表的,通常回调有单个事件实例,存储在回调接口的 EVENT 静态字段中,但也有其他的形式。例如,ClientTickEvents 将几个有关的事件分组在一起。

回调

Each event has a corresponding callback interface, conventionally named EventNameCallback. Callbacks are registered by calling register() on an event instance with an instance of the callback interface as the argument.

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.

  1. public class ExampleMod implements ModInitializer
  2. {
  3. [...]
  4.  
  5. @Override
  6. public void onInitialize()
  7. {
  8. AttackBlockCallback.EVENT.register((player, world, hand, pos, direction) ->
  9. {
  10. BlockState state = world.getBlockState(pos);
  11. /* Manual spectator check is necessary because AttackBlockCallbacks
  12.   fire before the spectator check */
  13. if (state.isToolRequired() && !player.isSpectator() &&
  14. player.getMainHandStack().isEmpty())
  15. {
  16. player.damage(DamageSource.field_5869, 1.0F);
  17. }
  18. return ActionResult.PASS;
  19. });
  20. }
  21. }

Fabric API 事件

玩家交互事件

注册表事件

战利品事件

LootTableLoadingCallback

关于使用 LootTableLoadingCallback 的例子,请参考此教程

世界事件

服务器事件

网络事件

zh_cn/tutorial/callbacks.1631853254.txt.gz · Last modified: 2021/09/17 04:34 by solidblock