Getting the entity responsible for ItemSpawnEvent

Discussion in 'Spigot Plugin Development' started by tremor, Jan 1, 2020.

  1. I'm trying to resolve the specific entity responsible for an ItemSpawnEvent - specifically, a chicken egg but this could have other applications. The only method I've been able to deduce so far is to get the location of the event and check for another entity at the same location. It works but it seems a bit roundabout - and in the case of a packed chicken farm, may not return the exact chicken. The reason here is for my PwnChickenLay plugin, a user requested a feature that a specifically "named" chicken be able to lay special eggs different than other chickens. Perhaps I'm overlooking something simple in the API docs but there doesn't seem to be a method to get the event source.

    Code (Java):
    Item test = (Item) event.getEntity();
    List<Entity> nearby = test.getNearbyEntities(0.01, 0.3, 0.01);
    for(int i = 0; i < nearby.size(); i++)
        if (nearby.get(i) instanceof Player) {
            //spawn event was from a Player
        else if (nearby.get(i) instanceof ItemFrame) {
            //spawn event was from an ItemFrame
        else if (nearby.get(i) instanceof Chicken) {
            //chicken laid an egg - here is where I'd check to see if the specific chicken had a name, potentially.
        else {
            // something else
  2. Not exactly a solution, but this seems like it would be pretty useful:

    Code (Java):

            Chicken chicken = ...;
            int ticksUntilEgg = ((CraftChicken) chicken).getHandle().eggLayTime;
    I'm not sure exactly how the NMS makes its way into the ItemSpawnEvent, but it seems like the egg is spawned before the lay time is reset. So in theory, when ItemSpawnEvent gets called, the chicken's lay time should be less than or equal to 0. Of course, a flaw with this approach is that two chickens can possibly lay an egg at the exact same time. However, you can combine this with your distance-based method and I think it'll be pretty reliable.
    • Informative Informative x 1
  3. Yes, this could work in combination. I just decided to log the nearby.size() method I am using in an overcrowded farm and to my surprise it's fairly accurate - it rarely returned 2 or more, so adding this method could almost make certain that, only a chicken named Bomb will lay primed TNT. I'm willing to live with the margin of error. Thanks! Just have to figure out NMS I've never really left the Spigot API farm.
    • Like Like x 1
  4. Sounds like heck of a plugin you're working on lol And glad you were able to figure it out!
  5. The core plugin has been released for years, - this is just a feature request.. I am surprised however there there is no method to get a spawn event's source, seems like it would be pretty useful.
    • Winner Winner x 1
  6. omg, how did I miss this? going to have to rewrite my listener but this is gold if the chicken/egg registers as a drop.