Finding the variant of non-block ItemType

I have seen a lot of posts on the forums here about how to get a variant given an ItemType that represents a block.

Examples I’ve found for how to get a variant for a block:

Neither of these work for me because my ItemType doesn’t have a BlockState associated with it, because it’s not a block. I’m trying to find in particular the variant for a spawning egg, but I’d prefer something more generic that can be extended to other types (such as leaves, dyed wool, etc)

Use the ItemStack's DataHolder methods.

For those who are curious, this is how I got it to work eventually:

        // stack is an ItemStack
        DataContainer cont = stack.toContainer();
        DataQuery query = DataQuery.of('/',"UnsafeDamage");
        if (!cont.contains(query)) {
            return -1;
        } else {
            return variant = (Integer)cont.get(query).orElse(-1);
        }

I’ve read on a few forum posts not to trust “UnsafeDamage” but I don’t think there’s anything else to go off of right now.
Might be a better way, but this is what I was able to get working.

You’d have to know some information of the ItemType, specifically, you could easily figure out what sort of values the ItemStack has with Data API’s methods: getValues() which you could easily filter the values that are any instances of ListValue or even CollectionValue. The point is: All you gain with the magic number system is ambiguity of “what does this number actually mean?” If you wanted the durability, easily use the Keys.DURABILITY of which you can get the maximum allowed durability and minimum allowed durability, etc. For actual variants like from ItemTypes.DYE, you can get the Keys.DYE_COLOR from the ItemStack. Anything else that I’m missing?

2 Likes

I was hoping there was a stable way to get the variant ID without having to do comparison on the actual ItemType. But if that’s the best way we’ve got, I guess I can move towards that. For now I’ve got something that seems to work, and that’s good enough for what I’m doing at the moment.

But you’d have to do comparison on the item type anyway. Say the variant is ‘2’, now what does that mean? If the item type is a plank, it’s the type of wood, if the item is wool then it’s the color, etc. At some point you’d have to actually know how to interpret the value,

That’s true. Most of the plugins I’m porting are already type-aware though, so I’ve already written that sort of code. I guess I’ll just make a wrapper for it instead, will be able to clean some stuff up, anyway.