TExcelTAD
Home › Godot 4 with GDScript › Resources & .tres Files

Resources & .tres Files

A resource is a data object that Godot can save to disk, load, share and edit in the Inspector. Textures, audio streams, fonts, materials, collision shapes, animations, tile sets and whole scenes (PackedScene) are all resources. Nodes do things in the tree; resources are things that nodes use.

Resources are reference-counted: they stay in memory while something holds them and are freed automatically afterwards. And Godot caches them by path: every load("res://slime.tres") in the game returns the same object. That cache is what makes resources cheap, and it is also the source of the most common resource bug, covered below.

Your own resource types

Extend Resource, give the class a name, and export the fields. This is how Godot projects store item definitions, enemy stats, dialogue lines, level data and settings:

gdscript
# res://data/enemy_stats.gd
class_name EnemyStats
extends Resource

@export var display_name := "Slime"
@export var max_hp := 10
@export var speed := 40.0
@export var drops: Array[String] = ["coin"]
@export var icon: Texture2D

Then create data files without code:

  1. In the FileSystem dock, right-click a folder and choose Create New > Resource....
  2. Search for EnemyStats, select it, click Create, and save as slime.tres.
  3. Double-click the file: the Inspector shows the exported fields. Fill them in and save.

The .tres file is plain text, so it diffs and merges well in Git:

ini
[gd_resource type="Resource" script_class="EnemyStats" format=3 uid="uid://c8k2w5n1slime"]

[ext_resource type="Script" path="res://data/enemy_stats.gd" id="1_stats"]

[resource]
script = ExtResource("1_stats")
display_name = "Slime"
max_hp = 12
drops = Array[String](["coin", "gel"])

A node exports a slot for it with @export var stats: EnemyStats, and you drag slime.tres into the slot. Five enemy scenes can now share one script and differ only in data. (.res is the binary form of the same thing: smaller and faster to load, but not readable in a diff.)

Note: The uid in the header is Godot's stable ID for the file (Godot 4.4 also writes .uid files next to scripts and shaders). It lets references survive a file being moved inside the editor. Commit .uid files to version control.

Saving and loading

ResourceSaver.save() writes any resource; load() (or ResourceLoader.load()) reads it back. At run time, save into user://: the per-user data folder (on Windows %APPDATA%\Godot\app_userdata\<project>). res:// is read-only in an exported game.

gdscript · try it yourself
extends SceneTree

func _init():
	var style := LabelSettings.new()      # a built-in resource: a text style for Labels
	style.font_size = 24
	style.font_color = Color.GOLD
	style.outline_size = 4
	var err := ResourceSaver.save(style, "user://title_style.tres")
	print("save: ", error_string(err))
	print(FileAccess.get_file_as_string("user://title_style.tres"))
	var loaded := load("user://title_style.tres") as LabelSettings
	print(loaded.font_size, " ", loaded.font_color, " same object? ", loaded == style)
	var again := load("user://title_style.tres")
	print("cached: ", again == loaded)
	quit()
save: OK
[gd_resource type="LabelSettings" format=3]

[resource]
font_size = 24
font_color = Color(1, 0.84313726, 0, 1)
outline_size = 4

24 (1.0, 0.8431, 0.0, 1.0) same object? false
cached: true

Only properties that differ from their defaults are written. The second load() returns the cached object, not a new copy.

Saving custom resources works the same way when the class lives in its own .gd file with class_name, as above. Be careful with save games, though: a .tres can reference any script, and loading a resource file runs that script's code. Loading a save file a player downloaded from the internet as a resource is a security hole. For save games, prefer JSON or ConfigFile, which hold only data; see Saving: FileAccess, ConfigFile & JSON.

The sharing gotcha

Because load() and preload() return the cached object, every enemy that uses slime.tres holds the same EnemyStats. If an enemy stores its current HP in that resource, damaging one slime damages them all:

gdscript · try it yourself
extends SceneTree

class Weapon extends Resource:
	@export var damage := 3

class EnemyStats extends Resource:
	@export var max_hp := 10
	@export var hp := 10
	@export var weapon: Weapon

class Enemy:
	var name: String
	var stats: EnemyStats
	func _init(p_name: String, p_stats: EnemyStats) -> void:
		name = p_name
		stats = p_stats

func report(enemies: Array) -> void:
	var parts: PackedStringArray = []
	for e in enemies:
		parts.append("%s hp=%d dmg=%d" % [e.name, e.stats.hp, e.stats.weapon.damage])
	print(", ".join(parts))

func _init():
	var slime_stats := EnemyStats.new()     # imagine: preload("res://data/slime.tres")
	slime_stats.weapon = Weapon.new()

	print("-- shared resource")
	var a := Enemy.new("A", slime_stats)
	var b := Enemy.new("B", slime_stats)
	a.stats.hp -= 4
	report([a, b])

	print("-- duplicate()")
	slime_stats.hp = 10
	var c := Enemy.new("C", slime_stats.duplicate())
	var d := Enemy.new("D", slime_stats.duplicate())
	c.stats.hp -= 4
	c.stats.weapon.damage = 99          # the sub-resource is still shared!
	report([c, d])

	print("-- duplicate_deep()")
	slime_stats.weapon.damage = 3
	var e := Enemy.new("E", slime_stats.duplicate_deep())
	var f := Enemy.new("F", slime_stats.duplicate_deep())
	e.stats.weapon.damage = 99
	report([e, f])
	quit()
-- shared resource
A hp=6 dmg=3, B hp=6 dmg=3
-- duplicate()
C hp=6 dmg=99, D hp=10 dmg=99
-- duplicate_deep()
E hp=10 dmg=99, F hp=10 dmg=3
  • duplicate() makes a shallow copy: the stats are separate, but resources inside it (the weapon) are still shared.
  • duplicate_deep() (Godot 4.5+) also copies sub-resources that are embedded rather than saved in their own file. duplicate(true) does the same for nested arrays and dictionaries. Pass RESOURCE_DEEP_DUPLICATE_ALL to copy even sub-resources that have their own file.

The cleanest fix is a design rule: resources hold definitions, nodes hold state. max_hp belongs in EnemyStats; the current hp belongs in a variable on the enemy node (var hp := stats.max_hp). Then nothing ever writes to the shared resource and sharing is pure benefit.

resource_local_to_scene

The same sharing happens with resources embedded in a scene. Every instance of coin.tscn shares its RectangleShape2D, its ShaderMaterial, its Gradient. Resizing one coin's shape at run time resizes all of them. Ticking Local to Scene (in the Inspector, under the resource's Resource section) makes Godot give each scene instance its own copy:

gdscript · try it yourself
extends Node

# frames: 0
func make_scene(local: bool) -> PackedScene:
	var root := Area2D.new()
	root.name = "Coin"
	var cs := CollisionShape2D.new()
	cs.name = "Shape"
	var rect := RectangleShape2D.new()
	rect.size = Vector2(16, 16)
	rect.resource_local_to_scene = local    # the "Local to Scene" checkbox
	cs.shape = rect
	root.add_child(cs)
	cs.owner = root
	var ps := PackedScene.new()
	ps.pack(root)                           # what saving coin.tscn does
	root.free()
	return ps

func _ready():
	for local in [false, true]:
		var scene := make_scene(local)
		var a := scene.instantiate()
		var b := scene.instantiate()
		add_child(a)
		add_child(b)
		var shape_a: RectangleShape2D = a.get_node("Shape").shape
		var shape_b: RectangleShape2D = b.get_node("Shape").shape
		shape_a.size = Vector2(64, 64)
		print("local_to_scene=", local, ": same object? ", shape_a == shape_b, ", b size = ", shape_b.size)
		a.free()
		b.free()
local_to_scene=false: same object? true, b size = (64.0, 64.0)
local_to_scene=true: same object? false, b size = (16.0, 16.0)

Use Local to Scene for resources you modify per instance (a hit-flash shader parameter, a per-enemy shape). Leave it off for everything else, because each copy costs memory and load time. For one-off cases, material = material.duplicate() in _ready() does the same thing in code.

Test yourself

Ten enemies use @export var stats: EnemyStats set to slime.tres. One enemy runs stats.hp -= 5. What happens?

  1. Only that enemy loses HP
  2. All ten see the lower HP, because they share the one cached resource
  3. The .tres file on disk changes
  4. Godot raises an error

After var copy = stats.duplicate(), which data is still shared with the original?

  1. Nothing
  2. Sub-resources stored inside it (for example a Weapon resource)
  3. Only ints and floats
  4. Everything

Why shouldn't a game load player-supplied save files as .tres resources?

  1. They are too large
  2. Resource files can reference scripts, so loading one can run arbitrary code
  3. They can't store integers
  4. user:// can't hold .tres files