How to add Items to Inventory

Godot Version

Godot 4.4

Question

I want to make it so that when you pick up a certain item in my 2D platformer. It will be added to your inventory. I already have a functioning inventory, I just don’t know how to add an item to an inventory slot when a certain thing happens.

Currently, I have the inventory file as a .tres file

Here is the code and node layout for my Inventory

And here is how I have my inventory slots coded and laid out

You didn’t show your code that handles the deletion of the item from the world after colliding with the player and the player script itself. These play an important role here.
Please also paste your code using preformatted text in the future.

In general, the code looks good so far, only missing a couple bits to make it fully functional.

Ideally, in your Player script, you should have a reference to the Inventory object.
Then, after colliding with the player, you access the inventory reference and add the item to your inventory.
The logic of adding the item to the slot can be a simple for loop checking each of the slots and if there is an empty slot - update the visual to show the correct item.

2 Likes

Okie dokie

Here’s the code for the item deletion:

extends Area2D


func _on_body_entered(body):
	if body is PizzaBoy:
		queue_free()

And here’s my player script so far:

extends CharacterBody2D
class_name PizzaBoy


@export var WALK_SPEED = 300.0
@export var JUMP_FORCE = -480
@export_range(0, 1) var DECEL = 0.2
@export_range(0, 1) var ACCEL = 0.2
@export var RUN_SPEED = 400.0
@export_range(0, 1) var DECEL_JUMP = 0.5

@export var inv: Inv


func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump.
	if Input.is_action_just_pressed("Jump") and is_on_floor():
		velocity.y = JUMP_FORCE
		
	if Input.is_action_just_released("Jump") and velocity.y < 0:
		velocity.y *= DECEL_JUMP

	var speed
	if Input.is_action_pressed("Sprint"):
		speed = RUN_SPEED
	else:
		speed = WALK_SPEED
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var direction := Input.get_axis("Left", "Right")
	if direction:
		velocity.x = move_toward(velocity.x, direction * speed, speed * ACCEL)
	else:
		velocity.x = move_toward(velocity.x, 0, WALK_SPEED * DECEL)

	move_and_slide()

I’ll try and do what you say with putting the item in an inventory slot, once I get the chance. Thank you for the help.

1 Like