... | ... | @@ -10,7 +10,42 @@ A method that is marked with ``@SubscribeEvent`` is an event handler. An event h |
|
|
|
|
|
Event classes may also be annotated with ``@Mod.EventBusSubscriber`` above their signature instead of registering them normally and this automatically registers the event handler to the Forge event bus when the ``@Mod`` class is constructed.
|
|
|
|
|
|
Lastly, if an event is cancelable, it will be marked with the ``@Cancelable`` annotation. It is very important to take note here that not all events are cancelable, attempting to do so if they do not have said annotation above them in their actual class causes an unsupported operation exception to be thrown, which will crash Minecraft.
|
|
|
##### 2.6.2.1: Canceling Events
|
|
|
|
|
|
Lastly, if an event is cancelable, above it will be marked with the ``@Cancelable`` annotation and ``event.setCanceled();`` will return true. It is very important to take note here that not all events are cancelable.
|
|
|
|
|
|
attempting to do so regardless of the true/false boolean put into ``setCanceled`` if they do not have said annotation above them in their actual class causes an unsupported operation exception to be thrown, which will crash Minecraft.
|
|
|
|
|
|
```java
|
|
|
@SubscribeEvent
|
|
|
public void cooldown(LivingEntityUseItemEvent.Start event) {
|
|
|
if (event.getEntityLiving() instanceof PlayerEntity) {
|
|
|
PlayerEntity player = (PlayerEntity) event.getEntityLiving();
|
|
|
//The above player-check is better than using Minecraft.getInstance().player, as it ensures multiplayer compatibility
|
|
|
if (PotionUtils.getPotion(event.getItem()) == Potion.byName("minecraft:night_vision")) {
|
|
|
event.setCanceled(true);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
```
|
|
|
|
|
|
This is an example of how to cancel an event, this one checks if the player has a night vision and prevents them from drinking it.
|
|
|
|
|
|
##### 2.6.2.2: Event Priority
|
|
|
|
|
|
``@SubscribeEvent(priority = EventPriority.HIGHEST)``
|
|
|
|
|
|
Priority can also be set for events and priority will make events with the higher priority run first in case two separate events are marked with a priority marked-subscribe event annotation.
|
|
|
|
|
|
Event priority enum values:
|
|
|
|
|
|
- HIGHEST
|
|
|
- HIGH
|
|
|
- NORMAL
|
|
|
- LOW
|
|
|
- LOWEST
|
|
|
|
|
|
Therefore, if you have five example events all with HIGHEST/HIGH/NORMAL/LOW/LOWEST, Forge will go down that priority list, running each event first based on which is the highest priority until it hits LOWEST.
|
|
|
|
|
|
Also, you may want to look at this image in case of troubleshooting your own events:
|
|
|

|
... | ... | |
... | ... | |