diff --git a/src/main/java/net/minestom/server/entity/Entity.java b/src/main/java/net/minestom/server/entity/Entity.java index deefbac68..eb8f0049c 100644 --- a/src/main/java/net/minestom/server/entity/Entity.java +++ b/src/main/java/net/minestom/server/entity/Entity.java @@ -270,6 +270,13 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev } + /** + * Called right before an entity is removed + */ + protected void despawn() { + + } + public boolean isOnGround() { return onGround || EntityUtils.isOnGround(this) /* backup for levitating entities */; } @@ -1484,11 +1491,20 @@ public class Entity implements Viewable, Tickable, Schedulable, Snapshotable, Ev */ public void remove() { if (isRemoved()) return; + + EventDispatcher.call(new EntityDespawnEvent(this)); + try { + despawn(); + } catch (Throwable t) { + MinecraftServer.getExceptionManager().handleException(t); + } + // Remove passengers if any (also done with LivingEntity#kill) Set passengers = getPassengers(); if (!passengers.isEmpty()) passengers.forEach(this::removePassenger); final Entity vehicle = this.vehicle; if (vehicle != null) vehicle.removePassenger(this); + MinecraftServer.process().dispatcher().removeElement(this); this.removed = true; Entity.ENTITY_BY_ID.remove(id); diff --git a/src/main/java/net/minestom/server/event/entity/EntityDespawnEvent.java b/src/main/java/net/minestom/server/event/entity/EntityDespawnEvent.java new file mode 100644 index 000000000..122f85b0b --- /dev/null +++ b/src/main/java/net/minestom/server/event/entity/EntityDespawnEvent.java @@ -0,0 +1,28 @@ +package net.minestom.server.event.entity; + +import net.minestom.server.entity.Entity; +import net.minestom.server.event.trait.EntityInstanceEvent; +import org.jetbrains.annotations.NotNull; + +/** + * Called right before an entity is removed + */ +public class EntityDespawnEvent implements EntityInstanceEvent { + + private final Entity entity; + + public EntityDespawnEvent(@NotNull Entity entity) { + this.entity = entity; + } + + /** + * Gets the entity who is about to be removed + * + * @return the entity + */ + @NotNull + @Override + public Entity getEntity() { + return entity; + } +}