Godot Version
4.1.2.stable
Question
I´m making an inventory system, and i have a function called “add_item_to_inventory” that, obviously, adds an item to the inventory array in player’s script by giving parameters of name, id, texture, description, and “on_use”, and that´s the problem.
“on_use” parameter is a function, but when i touch the button to execute the function “on_use”, the game crashes and the console says that the function is “null::on_use”, and i don’t know why and how to solve it. HELP!
Interactable.gd:
extends Area3D
@export var item_name: String
@export var item_id: int
@export var item_texture: Texture
@export var item_description: String
# Function to execute when "Use" button is touched
func on_use() -> Callable:
return func():
print("hello")
# Function to execute when player interact with something
func interact(interactor):
GameManager.add_item_to_inventory(interactor, item_name, item_id, item_texture, item_description, on_use)
queue_free()
game_manager.gd: (It has AutoLoad):
extends Node
var selected_item = null
func add_item_to_inventory(interactor, item_name: String, item_id: int, item_texture: Texture, item_description: String, on_use: Callable):
var found_empty_slot = false
# Add item to inventory
for i in range(interactor.inventory.size()):
if interactor.inventory[i] == null:
interactor.inventory[i] = {
"name": item_name,
"id": item_id,
"image": item_texture,
"description": item_description,
"on_use": on_use
}
found_empty_slot = true
break
InventoryDisplay.gd:
extends Control
var on_item_use = null
@onready var slots = [
$InventoryGrid/Slot1,
$InventoryGrid/Slot2,
$InventoryGrid/Slot3,
$InventoryGrid/Slot4,
$InventoryGrid/Slot5,
$InventoryGrid/Slot6,
]
func update_inventory_display(inventory):
$ItemName.text = ""
$ItemDescription.text = ""
on_item_use = null
for i in range(slots.size()):
if inventory[i] != null:
# Update images of all items
slots[i].get_node("TextureRect").texture = inventory[i]["image"]
# Update display information
if slots[i] == GameManager.selected_item:
$ItemName.text = inventory[i]["name"]
$ItemDescription.text = inventory[i]["description"]
on_item_use = inventory[i]["on_use"]
# When "Use item" button is touched
func _on_use_item_pressed():
on_item_use.call() # Here is when i call the function and the game crashes!
Slot.gd:
extends Button
@export var inventory_display : Control
@export var player : CharacterBody3D
func _on_pressed():
GameManager.selected_item = self
inventory_display.update_inventory_display(player.inventory)