hollow-cube/entity-despawn-hooks (#63)

* Add Entity::despawn

* Clarify that despawn() is not at risk of being ignored

* Make despawn() protected

(cherry picked from commit 9e27053b15)
This commit is contained in:
Samuel 2023-09-26 09:28:39 -04:00 committed by Matt Worzala
parent 926871c86e
commit b1b33b9df8
2 changed files with 44 additions and 0 deletions

View File

@ -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<Entity> 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);

View File

@ -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;
}
}