+1 vote

I'm fairly new to Godot and I may have trouble explaining what I'm asking here, so bear with me;

I'm working on my player's inventory, and to do so I need Items. In my previous experience in game dev I would have an "Item" class, and when I wanted to spawn an item in that can be collected and stored in the inventory, I would create an instance of said Item (Item coin = new Item())

What is the best way to do this in Godot? From my understanding I can only attach scripts to existing objects, what if I want to be able to add an item to the inventory without adding an object to the scene?

in Engine by (55 points)

You can have scripts not attached to any node by using the global /Auto load feature described here

Also, you could create a node and not make it visible

Goodluck

1 Answer

0 votes
Best answer

You can create an Item node that is just an extension of Node, with a script listing the item's attributes.

For example,

extends Node

# item attributes
item_name = "sword"
item_description = "super cool sword that shines and stuff"
count = 1
durability = 25
attack_power = 50

Then, you can create an ItemPickUp node which you display in your scene.

You can associate items with the pickup nodes by exporting a packed scene variable. That way, you can select which item you want associated with the pickup directly from the inspector.

export(PackedScene) var associated_item_scene 

When the player interacts with the item pickup node (for example, collides with an Area2D child of it), spawn the associated item in the player's inventory.

# put this in your pickup node (probably under body_entered signal)
var new_item = associated_item_scene.instance()
player.inventory.append(new_item)

You can store the item in an array called inventory. Just because you instanced the node doesn't mean you need to add it to your tree. You can just store it in the array.

by (1,602 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.