← Pixel Dreamer Studio

Count and take crafting items from every stack

Add up the item over all slots before crafting, then take it stack by stack and empty the slots that run out.

Finding the first stack of an item and checking its count misses everything in the other stacks. In our Godot 4.7 test the player had 9 iron ore in stacks of 3, 4 and 2, and a recipe that needs 5 said no. Taking the 5 from that first stack left it at -2. Count over every slot first, then take what you need stack by stack.

The code

Call count_of(slots, item) to show how many the player has and to grey out recipes they cannot make. Call take(slots, item, amount) when crafting: it returns false and takes nothing if there is not enough. When a recipe needs several items, check all their counts first, then take them all.

extends Node
## Count and take crafting items across every inventory stack.
## slots is an Array of Dictionaries like {"item": "iron_ore", "count": 4}, or null for an empty slot.


static func count_of(slots: Array, item: String) -> int:
	var n := 0
	for s in slots:
		if s != null and s.item == item:
			n += s.count
	return n


static func take(slots: Array, item: String, amount: int) -> bool:
	if count_of(slots, item) < amount:
		return false  # check first, so a failed craft takes nothing
	for i in slots.size():
		var s = slots[i]
		if s == null or s.item != item:
			continue
		var used: int = mini(s.count, amount)
		s.count -= used
		amount -= used
		if s.count == 0:
			slots[i] = null  # empty the slot
		if amount == 0:
			break
	return true

What we measured

An inventory of iron ore 3, wood 5, iron ore 4, an empty slot and iron ore 2: 9 iron ore in total, and a recipe that needs 5. Two runs with the same results.

Why it happens

Stacks have a size limit, or the player splits them, so the same item often sits in several slots. A check that stops at the first match only sees part of what the player has, and taking more than that stack holds drives it below zero. Checking the total before taking anything also means a failed craft never eats half the ingredients.

What to change

Recipes that work in any order: crafting recipe check. A gathering hit that feels solid: shake an object when hit. Hold a button to craft: a hold bar that takes the same time at any frame rate.

Ready-made gathering effects: Crafting & Gathering VFX for Godot 4 has 28 presets in Stylized and Retro PSX looks, including Mine Stone, Mine Crystal, Mine Gold Ore, Chop Wood and Gather Herb.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Crafting & Gathering VFX for Godot 4 has 28 ready-made crafting and gathering effects in Stylized and Retro PSX looks, including Mine Stone, Mine Gold Ore, Chop Wood and Gather Herb.

More how-tos for Crafting & Gathering VFX for Godot 4: Shake a rock or tree when hit, without it drifting · A hold-to-craft bar that takes the same time at any frame rate and finishes once

More how-tos: Game systems