When you want to spawn a custom entity, e.g. with a custom name or certain items equipped, you must use the method World#spawn(Location, Class<T extends Entity>, Consumer<T>)
unless you give a shit about compatibility with other plugins. I’ll explain why.
The shitty way
Usually, you can easily spawn entities like this:
Pig myPig = location.getWorld().spawn(location, Pig.class); // or alternatively: Pig myPig = (Pig) location.getWorld().spawnEntity(location, EntityType.PIG);
That is fine, as long as you don’t want to change any data of that entity right away. For example, let’s assume that we want to give our pig a custom name, let’s say oliver193
. You might be tempted to simply do it like this:
Pig myPig = location.getWorld().spawn(location, Pig.class); myPig.setCustomName("oliver193"); myPig.setCustomNameVisible(true);
Never ever do that unless you don’t care about compatibility with other plugins. Let’s just imagine for a second that we have another plugin that simply prints a message to console whenever a named entity spawns:
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onNamedEntitySpawn(CreatureSpawnEvent event) { String customName = event.getEntity().getCustomName(); if(customName == null) return; getLogger().info("A custom entity named \"" + customName + "\" spawned at " + event.getEntity().getLocation()); }
Obviously, this will not work, since we spawned the Pig before giving it a custom name. That sucks.
The proper way
However, we can easily achieve the same thing in a proper way by actually setting the data before adding the entity to the world, by providing a Consumer<Pig> to the spawn method:
Pig myPig = location.getWorld().spawn(location, Pig.class, (pig) -> { pig.setCustomName("oliver193"); pig.setCustomNameVisible(true); });
Join my Discord Server for feedback or support. Just check out the channel #programming-help
🙂
oliver193!?!?!?
no way its not oliver193 commenting about oliver193 i wonder if thats ntdi