[SOLVED] Creating an Item Entity

Hello guys,
I can’t seem to figure out how to create an Item (Entity) in the world from an ItemStack.
I already tried to use the Extent.createEntity() method, but without much luck.

Thanks for any help, nylser :smiley:

Here is how i would do it. I have not tested the code nor do I have SpongeAPI so some things maybe a tiny bit wrong

ItemStack stack;
World world;
Vector3i vector;
Item item = (Item) world.createEntity(EntityTypes.DROPPED_ITEM,  vector) ;
RepresentedItemData data = item.getOrCreate(RepresentedItemData.class).get();
data.setValue(stack);
world.spawnEntity(item);
1 Like

This code looks good, but it only seems to create a dropped stone item in the world.

This is the more efficient way to do it, but I have tried it and it does not work. Im out of ideas now.

ItemStack stack;
World world;
Vector3i vector;
Item item = (Item) world.createEntity(EntityTypes.DROPPED_ITEM,  vector) ;
item.getItemData().setValue(stack);
world.spawnEntity(item);
1 Like

You need to offer the data back to the entity. No use changing it without re-applying it.
item.offer(item.getItemData().setValue(stack));

2 Likes

Thank you very much! this worked :slight_smile:

This code doesn’t seem to work with the newer Sponge API.

  • DROPPED_ITEM is no longer a thing in EntityTypes
  • Entities can’t be cast to Items
  • RepresentedItemData (the thing returned from item.getItemData()) doesn’t have a set method that takes in an ItemStack anymore.
  • world.spawnEntity now requires a Cause

Does anybody know the new way to “drop” an item in the world at a location? I’ll see if I can figure it out on my own but if someone else already knows how to do it that would help.

You would need to spawn an entity into the world as you normally would, with a few minor adjustments. Take a look at the entity docs to see how spawning an entity would normally occur. Note that SpawnCauses are currently not implemented.

Here is an example of spawning an ItemStack in:

Location<World> loc = ...;
ItemStack stack = ...;
Extent extent = loc.getExtent();
// Use the ITEM type
Optional<Entity> optional = extent.createEntity(EntityTypes.ITEM, loc.getBlockPosition());
if (optional.isPresent()) {
    Entity entity = optional.get();
    // We need to specify the ItemStack that this entity should represent
    entity.offer(Keys.REPRESENTED_ITEM, stack.createSnapshot());
    // If running this from a command, use the CommandSource, rather than 'this'
    extent.spawnEntity(entity, Cause.of(this));
}

There is a PR open on the docs on things such as spawning items, creating items, and such if you wish to look through it.

Thanks, I’ll give that a shot.