Skip to content

Commit

Permalink
add side checks in the event handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
IchHabeHunger54 committed Jan 31, 2024
1 parent c49ff55 commit 242abf0
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions docs/concepts/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ public class YourMod {

// Heals an entity by half a heart every time they jump.
private static void onLivingJump(LivingJumpEvent event) {
event.getEntity().heal(1);
Entity entity = event.getEntity();
// Only heal on the server side
if (!entity.level().isClientSide()) {
entity.heal(1);
}
}
}
```
Expand All @@ -34,7 +38,10 @@ Alternatively, event handlers can be annotation-driven by creating an event hand
public class EventHandler {
@SubscribeEvent
public void onLivingJump(LivingJumpEvent event) {
event.getEntity().heal(1);
Entity entity = event.getEntity();
if (!entity.level().isClientSide()) {
entity.heal(1);
}
}
}

Expand All @@ -52,7 +59,10 @@ You can also do it statically. Simply make all event handlers static, and instea
public class EventHandler {
@SubscribeEvent
public static void onLivingJump(LivingJumpEvent event) {
event.getEntity().heal(1);
Entity entity = event.getEntity();
if (!entity.level().isClientSide()) {
entity.heal(1);
}
}
}

Expand All @@ -64,10 +74,6 @@ public class YourMod {
}
```

:::info
`@SubscribeEvent` annotated methods must not be `private`. Any out of `package-private`, `protected` and `public` will work.
:::

### `@Mod.EventBusSubscriber`

We can go one step further and also annotate the event handler class with `@Mod.EventBusSubscriber`. This annotation is discovered automatically by NeoForge, allowing you to remove all event-related code from the mod constructor. In essence, it is equivalent to calling `NeoForge.EVENT_BUS.register(EventHandler.class)` at the end of the mod constructor. This means that all handlers must be static, too.
Expand All @@ -79,7 +85,10 @@ While not required, it is highly recommended to specify the `modid` parameter in
public class EventHandler {
@SubscribeEvent
public static void onLivingJump(LivingJumpEvent event) {
event.getEntity().heal(1);
Entity entity = event.getEntity();
if (!entity.level().isClientSide()) {
entity.heal(1);
}
}
}
```
Expand Down

0 comments on commit 242abf0

Please sign in to comment.