Excellent question! Using Resource for character attributes is a fantastic, data-driven approach in Godot. It's one of the most powerful and flexible ways to handle this common problem.
Since you've already created the basic Attribute resources, you're 90% of the way there. The "best way" is to combine them into a Component-based system.
Here's a breakdown of the most robust and scalable method, followed by simpler alternatives and their trade-offs.
Recommended: The Component-Based Approach
This approach treats your character's stats as a separate component (a Node) that you can attach to any character, whether it's the player or an NPC.
The Goal:
- Define attributes as reusable
Resource files (.tres).
- Create a
StatsComponent node that holds and manages all attributes for a character.
- Attach this
StatsComponent to your Player and NPC scenes.
- Easily access and modify stats from your character's main script.
Step 1: Refine Your Attribute Resource
Let's ensure your Attribute resource is set up for success. A good pattern is to have a base value and a current value, along with signals to react to changes.
File: res://attributes/attribute.gd
@tool
class_name Attribute
extends Resource
# Signal emitted when the value changes. Great for updating UI or checking for death.
signal value_changed(new_value)
# The default/base value of this attribute. Set this in the Inspector.
@export var base_value: float = 100.0
# The current value. We use a setter to emit the signal automatically.
var _current_value: float
var current_value:
get:
return _current_value
set(value):
_current_value = clamp(value, 0, base_value) # Or whatever logic you need
if value_changed.is_connected():
value_changed.emit(_current_value)
# When the resource is first used, or the game starts, initialize current value.
func _init():
_current_value = base_value
func reset():
current_value = base_value
Now, create your actual attribute files in the FileSystem dock:
- Right-click -> New Resource... -> Select
Attribute.
- Save it as
health.tres. In the Inspector, set its base_value to 100.
- Create
mana.tres (base_value: 50), strength.tres (base_value: 10), etc.
Step 2: Create the StatsComponent Node
This is the heart of the system. It's a node that will hold a dictionary of all the attributes for a character.
File: res://components/stats_component.gd
class_name StatsComponent
extends Node
# In the Inspector, you will drag your .tres files into this array.
@export var attribute_definitions: Array[Attribute]
# A dictionary to hold the LIVE instances of our attributes.
# The key will be the resource's name (e.g., "health").
var attributes: Dictionary = {}
func _ready():
# This is the most IMPORTANT step!
# We must DUPLICATE the resources. Otherwise, every single enemy
# would share the same health resource instance!
for attr_resource in attribute_definitions:
if attr_resource:
# Get the name from the resource file path (e.g., "health.tres" -> "health")
var attr_name = attr_resource.resource_path.get_file().get_basename()
# Duplicate the resource and store it in our live dictionary
attributes[attr_name] = attr_resource.duplicate()
# --- Helper Functions ---
# Check if the component has a specific attribute
func has_attribute(attr_name: String) -> bool:
return attributes.has(attr_name)
# Get the entire attribute resource (useful for getting base_value)
func get_attribute(attr_name: String) -> Attribute:
return attributes.get(attr_name)
# Get the current value of an attribute
func get_value(attr_name: String) -> float:
var attr = get_attribute(attr_name)
if attr:
return attr.current_value
return 0.0 # Or handle error appropriately
# Set the current value of an attribute
func set_value(attr_name: String, new_value: float):
var attr = get_attribute(attr_name)
if attr:
attr.current_value = new_value
# A convenient way to connect to an attribute's 'value_changed' signal
func connect_to_attribute(attr_name: String, callable: Callable):
var attr = get_attribute(attr_name)
if attr:
attr.value_changed.connect(callable)
Step 3: Assemble Your Player and NPCs
Now, you can build any character using this component.
-
Create your Player scene (e.g., Player.tscn based on CharacterBody2D).
-
Add a StatsComponent node as a child of the Player root node.
-
Select the StatsComponent in the Scene Tree.
-
In the Inspector, find the Attribute Definitions array. Set its size and drag your health.tres, mana.tres, etc. files into the slots.
-
Repeat for NPCs! Create a Goblin.tscn. Add a StatsComponent. Maybe the Goblin only has health.tres and strength.tres. You can configure this per-NPC. For a "Goblin Mage", you could add mana.tres to its StatsComponent without changing any scripts!
Scene Tree Example:
- Player (CharacterBody2D)
- Sprite2D
- CollisionShape2D
- StatsComponent <-- Your stats are managed here
- PlayerController.gd (script attached to root)
Step 4: Use the System in Code
In your player or NPC script, you can now easily interact with the stats.
File: res://player/player_controller.gd
extends CharacterBody2D
# Get a reference to the component on ready.
@onready var stats: StatsComponent = $StatsComponent
func _ready():
# Connect to signals. This is great for UI updates or death checks.
stats.connect_to_attribute("health", _on_health_changed)
# Print initial strength
var current_strength = stats.get_value("strength")
print("My starting strength is: ", current_strength)
func take_damage(amount: float):
var current_health = stats.get_value("health")
stats.set_value("health", current_health - amount)
print("Ouch! Took %s damage. Health is now %s" % [amount, stats.get_value("health")])
func _on_health_changed(new_health: float):
print("Health changed! New value: ", new_health)
if new_health <= 0:
die()
func die():
print("I have died!")
queue_free()
Why is this the "Best Way"?
- Data-Driven: Non-programmers (designers) can create new enemy types and balance stats just by creating and editing
.tres files. No code changes needed.
- Decoupled: Your character's logic (
PlayerController.gd) doesn't care how stats are stored, it just asks the StatsComponent for them. This keeps your code clean.
- Scalable: Need to add a "Luck" attribute? Create
luck.tres, add it to the StatsComponent array in the Inspector, and you're done.
- Reusable: The
StatsComponent and Attribute resources can be used for players, enemies, destructible chests, anything with health.
- Safe Instancing: The
duplicate() call in StatsComponent is critical. It ensures that when you have 10 Goblins in your level, they don't all share the same health bar. Each one gets its own unique copy of the stats.
Alternative (Simpler) Approaches
1. The Single Stats Resource
Instead of many small Attribute resources, you create one big resource that holds all possible stats.
File: character_stats.gd
class_name CharacterStats
extends Resource
@export var health: float = 100.0
@export var mana: float = 50.0
@export var strength: float = 10.0
@export var defense: float = 5.0
# ...etc
Usage:
In your character script:
@export var stats: CharacterStats
var live_stats: CharacterStats
func _ready():
# You still MUST duplicate it!
live_stats = stats.duplicate()
func take_damage(amount):
live_stats.health -= amount
- Pros: Simpler to set up. All stats for a character type are in one file (e.g.,
goblin_stats.tres).
- Cons: Less flexible. If you want to add a "Psionic Resistance" stat that only one specific alien NPC has, you have to add it to the
CharacterStats resource, which means every other character now has that property (even if it's unused).
2. Simple Export Variables (The "Quick and Dirty" Way)
Just put variables directly in your character script.
In player.gd:
@export var health: int = 100
@export var mana: int = 50
- Pros: Extremely fast for prototyping or for games with very few, simple stats.
- Cons: Not scalable at all. Blends data and logic. Can't reuse stat "definitions". Becomes unmanageable with more than a handful of stats.
Conclusion:
For any project that you expect to grow, the Component-Based Approach is by far the most powerful, clean, and scalable solution. It perfectly leverages Godot's Resource and Node systems and is a pattern you will see in many professional-quality Godot projects. You are on the exact right track by starting with Resources.