77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(godot): add godot-3d-essentials, godot-resources, godot-audio skills
AbhishekBarali159cd72678082
diff --git a/skills/godot/godot-3d-essentials/SKILL.md b/skills/godot/godot-3d-essentials/SKILL.mdnew file mode 100644index 0000000..ecd1571--- /dev/null+++ b/skills/godot/godot-3d-essentials/SKILL.md@@ -0,0 +1,141 @@+---+name: godot-3d-essentials+description: >+ Set up a Godot 4.x 3D scene: Node3D transforms, Camera3D, lighting+ (DirectionalLight3D/OmniLight3D), WorldEnvironment for sky/ambient/tonemap/post,+ MeshInstance3D materials, and GridMap for tile-based 3D levels. Use when building+ a 3D scene in a Godot project, placing cameras/lights, configuring environment and+ post-processing, or working with Node3D/.tscn 3D content and GridMap.+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot 3D Essentials (4.x)++Assemble a working 3D scene: transforms, camera, lights, environment/post, materials, and+`GridMap` blockouts. Targets **Godot 4.3+**.++## When to use++- Use when starting or fixing a 3D scene: positioning a `Camera3D`, adding lights, setting+ up a `WorldEnvironment` (sky, ambient, tonemap, glow/SSAO), assigning materials, or+ building levels with `GridMap`.++**When *not* to use:** writing spatial shaders → `godot-shaders`; 3D physics bodies and+raycasts → `godot-physics`; character animation blending → `godot-animation`; full FPS+template → the `fps-shooter` genre skill.++## Core workflow++1. **Everything 3D is a `Node3D`** with a `Transform3D` (position, rotation basis, scale).+ Move with `global_position`, rotate with `rotate_y(angle)` or `look_at(target)`.+2. **Add a `Camera3D`.** Mark it `current` (or call `make_current()`); set `fov`, `near`,+ `far`. Parent it to a rig/pivot for orbit or follow cameras.+3. **Light the scene.** A `DirectionalLight3D` is the sun; `OmniLight3D`/`SpotLight3D` are+ local. Enable shadows per light. Without lights and ambient, surfaces render black.+4. **Add a `WorldEnvironment`** with an `Environment` resource: background (sky/color),+ ambient light, tonemap, and post (glow, SSAO, fog, adjustments).+5. **Give meshes materials** (`StandardMaterial3D` or a `ShaderMaterial`) on+ `MeshInstance3D`.+6. **Block out levels with `GridMap`**, which places `MeshLibrary` items on a 3D grid+ (the 3D analog of a tilemap).++## Patterns++### 1. A follow camera (third-person, smoothed)++```gdscript+extends Camera3D++@export var target: Node3D+@export var offset := Vector3(0, 4, 8)+@export var smooth := 6.0++func _physics_process(delta: float) -> void:+ if target == null:+ return+ var desired := target.global_position + offset+ global_position = global_position.lerp(desired, smooth * delta) # smooth follow+ look_at(target.global_position, Vector3.UP) # face the target+```++### 2. Sun + environment in code++```gdscript+func _ready() -> void:+ var sun := DirectionalLight3D.new()+ sun.rotation_degrees = Vector3(-45, -30, 0)+ sun.shadow_enabled = true+ add_child(sun)++ var we := WorldEnvironment.new()+ var env := Environment.new()+ env.background_mode = Environment.BG_SKY+ env.sky = Sky.new()+ env.sky.sky_material = ProceduralSkyMaterial.new()+ env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY+ env.tonemap_mode = Environment.TONE_MAPPER_FILMIC+ env.glow_enabled = true+ we.environment = env+ add_child(we)+```++### 3. Assign a StandardMaterial3D from code++```gdscript+func tint_mesh(mesh: MeshInstance3D, color: Color) -> void:+ var mat := StandardMaterial3D.new()+ mat.albedo_color = color+ mat.metallic = 0.0+ mat.roughness = 0.6+ mat.emission_enabled = true+ mat.emission = color * 0.3+ mesh.material_override = mat # overrides the mesh's surface materials+```++### 4. Place tiles into a GridMap++```gdscript+@onready var grid: GridMap = $GridMap # cell_size + mesh_library set in the editor++func build_floor(width: int, depth: int, item_id: int) -> void:+ for x in width:+ for z in depth:+ # set_cell_item(Vector3i cell, int item, orientation = 0)+ grid.set_cell_item(Vector3i(x, 0, z), item_id)+```++## Pitfalls++- **Scene renders black** → no lights and no ambient. Add a `DirectionalLight3D` and/or a+ `WorldEnvironment` with ambient/sky. New scenes have neither by default.+- **No camera / wrong camera.** If nothing shows, no `Camera3D` is `current`. Set+ `current = true` or `make_current()`; only one camera renders per viewport.+- **Confusing local vs global transforms.** `position`/`rotation` are relative to the+ parent; `global_position`/`global_transform` are world space. Mixing them under a rotated+ parent gives surprising results. `look_at` uses global coordinates.+- **Scaling physics/lights.** Non-uniform `scale` on a `Node3D` distorts child collisions+ and lights; prefer scaling the mesh asset or using uniform scale.+- **Forgetting `from`/`up` in `look_at`.** `look_at(target, up)` — a target equal to the+ node's position, or an `up` parallel to the look direction, produces NaNs/flips.+- **GridMap with no `MeshLibrary`** places nothing. Create a `MeshLibrary` (from scenes)+ and assign it; `set_cell_item(cell, -1)` clears a cell.+- **HDR/glow too strong** → check `tonemap_mode` and glow thresholds; raw emissive values+ bloom hard under filmic tonemapping.++## References++- For Transform3D math, camera projection modes, light/shadow params, the full+ Environment/post-processing options, `MeshLibrary` creation, and `ReflectionProbe`/+ `LightmapGI` lighting, read `references/scene-and-environment.md`.++## Related skills++- `godot-physics` — 3D bodies, areas, and raycasts.+- `godot-shaders` — spatial shaders for custom 3D surfaces.+- `godot-animation` — `AnimationTree` for 3D characters.+- `fps-shooter` — composes 3D movement, input, and AI into a game.diff --git a/skills/godot/godot-3d-essentials/references/scene-and-environment.md b/skills/godot/godot-3d-essentials/references/scene-and-environment.mdnew file mode 100644index 0000000..6339201--- /dev/null+++ b/skills/godot/godot-3d-essentials/references/scene-and-environment.md@@ -0,0 +1,86 @@+# 3D scene & environment reference (Godot 4.3+)++Depth companion to `godot-3d-essentials`.++## Transform3D++A `Node3D` has a `Transform3D` = `Basis` (3x3 rotation/scale) + `origin` (Vector3).++```gdscript+global_position = Vector3(1, 0, 2)+rotate_y(deg_to_rad(90)) # rotate about local Y+rotation_degrees = Vector3(0, 45, 0)+look_at(target_global_pos, Vector3.UP) # global-space orientation+transform = transform.translated_local(Vector3.FORWARD * 2.0) # move along local -Z+basis = basis.orthonormalized() # fix drift after many rotations+```++Godot 3D convention: **-Z is forward**, +Y is up, +X is right.++## Camera3D++- `projection`: `PROJECTION_PERSPECTIVE` (fov) or `PROJECTION_ORTHOGONAL` (size).+- `fov`, `near`, `far`, `current`, `make_current()`, `clear_current()`.+- `project_ray_origin(screen_pos)` / `project_ray_normal(screen_pos)` for click-to-world+ picking (combine with a physics raycast).+- `unproject_position(world_pos)` → screen position (e.g. floating health bars).+- For follow/orbit, parent the camera to a pivot `Node3D` and rotate the pivot.++## Lights++| Node | Role | Key props |+|------|------|-----------|+| `DirectionalLight3D` | Sun (parallel rays) | `shadow_enabled`, `light_energy`, `directional_shadow_mode` |+| `OmniLight3D` | Point light | `omni_range`, `light_energy`, `shadow_enabled` |+| `SpotLight3D` | Cone | `spot_range`, `spot_angle`, `shadow_enabled` |++Common: `light_color`, `light_energy`, `light_indirect_energy`, shadow bias settings.+Too many shadow-casting lights hurts performance — bake static lighting where possible.++## Environment & post-processing++`WorldEnvironment.environment` (an `Environment` resource):++- **Background:** `BG_CLEAR_COLOR`, `BG_COLOR`, `BG_SKY` (with a `Sky` ++ `ProceduralSkyMaterial`/`PanoramaSkyMaterial`).+- **Ambient:** `ambient_light_source` (sky/color/disabled), `ambient_light_color`,+ `ambient_light_energy`.+- **Tonemap:** `tonemap_mode` (LINEAR, REINHARD, FILMIC, ACES), `tonemap_exposure`,+ `tonemap_white`.+- **Post:** `glow_enabled` (+ bloom/levels), `ssao_enabled`, `ssil_enabled`,+ `sdfgi_enabled` (real-time GI), `fog_enabled`/`volumetric_fog_enabled`,+ `adjustment_enabled` (brightness/contrast/saturation + color correction).++A `CameraAttributes` resource (Practical/Physical) adds DOF, auto-exposure, and exposure+controls, assigned on the camera or environment.++## Materials++`StandardMaterial3D` (PBR) key fields: `albedo_color`/`albedo_texture`, `metallic`,+`roughness`, `normal_enabled`+`normal_texture`, `emission_enabled`+`emission`,+`transparency` (`TRANSPARENCY_ALPHA`/`ALPHA_SCISSOR`), `cull_mode`, `shading_mode`+(`SHADING_MODE_PER_PIXEL` / `UNSHADED`). Apply via `MeshInstance3D.material_override` (all+surfaces) or `set_surface_override_material(i, mat)` (per surface). `ORMMaterial3D` packs+occlusion/roughness/metallic into one texture.++## GridMap & MeshLibrary++1. Build a scene where each child is a mesh + optional collision; export it as a+ `MeshLibrary` (Scene > Export As > MeshLibrary), or convert a scene in the editor.+2. Assign the `MeshLibrary` to the `GridMap.mesh_library` and set `cell_size`.+3. Paint in the editor, or from code:+ ```gdscript+ grid.set_cell_item(Vector3i(x, y, z), item_id, orientation)+ grid.get_cell_item(Vector3i(x, y, z)) # -1 if empty (GridMap.INVALID_CELL_ITEM)+ grid.get_used_cells()+ grid.clear()+ grid.map_to_local(cell) / grid.local_to_map(pos)+ ```+ Orientation comes from `GridMap.get_orthogonal_index_from_basis(basis)`.++## Baked lighting & probes++- `LightmapGI` — bake static GI into lightmaps for static geometry (mark meshes "bake").+- `ReflectionProbe` — local cubemap reflections for an area.+- `VoxelGI` / `SDFGI` — dynamic GI (heavier). Use baked lightmaps for ship-quality static+ scenes and reserve real-time GI for dynamic needs.diff --git a/skills/godot/godot-audio/SKILL.md b/skills/godot/godot-audio/SKILL.mdnew file mode 100644index 0000000..a377e2e--- /dev/null+++ b/skills/godot/godot-audio/SKILL.md@@ -0,0 +1,128 @@+---+name: godot-audio+description: >+ Play and mix audio in Godot 4.x: AudioStreamPlayer (2D/3D variants), audio buses+ with volume/mute and effects, music vs SFX routing, db/linear volume, and precise+ sync-to-beat playback timing. Use when playing sounds or music in a Godot project,+ routing AudioStreamPlayer nodes to buses, adjusting bus volume via AudioServer, or+ syncing gameplay to the beat.+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot Audio (4.x)++Play SFX and music, route them through buses, control volume in decibels, and time+gameplay to the beat. Targets **Godot 4.3+**.++## When to use++- Use when playing sound effects or music, routing audio to buses (Master/Music/SFX),+ adjusting volume/mute from code, adding bus effects (reverb, compressor), positional 3D+ audio, or syncing events to music.++**When *not* to use:** engine-agnostic audio *design* (adaptive music structure, mixing+philosophy, ducking patterns) → `audio-design`; importing/encoding assets outside Godot.++## Core workflow++1. **Pick the player node:**+ - `AudioStreamPlayer` — non-positional (music, UI, global SFX).+ - `AudioStreamPlayer2D` / `AudioStreamPlayer3D` — positional; volume/pan from distance.+2. **Assign an `AudioStream`** to `stream` (`.ogg` for music/loops, `.wav` for short SFX)+ and `play()`. Set `autoplay` for music that starts with the scene.+3. **Route to a bus.** Set the player's `bus` to a named bus (e.g. `"Music"`, `"SFX"`).+ Define buses in the Audio panel (bottom dock); each can have volume, mute, solo, and+ effects.+4. **Control volume in dB**, not linear (audio is logarithmic). `0 dB` = unchanged,+ `-80 dB` ≈ silent. Convert with `linear_to_db`/`db_to_linear`.+5. **Drive volume/mute from code** with `AudioServer` by bus index.+6. **For rhythm**, compute precise playback time using output latency compensation.++## Patterns++### 1. One-shot SFX (fire-and-forget)++```gdscript+@onready var sfx: AudioStreamPlayer = $Sfx # stream assigned in the editor++func play_jump() -> void:+ sfx.pitch_scale = randf_range(0.95, 1.05) # slight variation avoids fatigue+ sfx.play()++# For many overlapping copies, use an AudioStreamPlayer with an+# AudioStreamPolyphonic stream, or spawn short-lived players and free on `finished`.+```++### 2. Set a bus's volume and mute via AudioServer++```gdscript+func set_music_volume(linear_0_to_1: float) -> void:+ var bus := AudioServer.get_bus_index("Music")+ # Convert a 0..1 slider to decibels; clamp avoids -inf at 0.+ AudioServer.set_bus_volume_db(bus, linear_to_db(maxf(linear_0_to_1, 0.0001)))++func toggle_sfx(muted: bool) -> void:+ AudioServer.set_bus_mute(AudioServer.get_bus_index("SFX"), muted)+```++### 3. Crossfade between two music tracks++```gdscript+@onready var a: AudioStreamPlayer = $MusicA+@onready var b: AudioStreamPlayer = $MusicB++func crossfade_to(stream: AudioStream, secs := 1.5) -> void:+ b.stream = stream+ b.volume_db = -40.0+ b.play()+ var tw := create_tween().set_parallel(true)+ tw.tween_property(a, "volume_db", -40.0, secs) # fade out current+ tw.tween_property(b, "volume_db", 0.0, secs) # fade in next+ tw.chain().tween_callback(a.stop)+ var tmp := a; a = b; b = tmp # swap roles+```++### 4. Beat-accurate timing (compensate for output latency)++```gdscript+@onready var music: AudioStreamPlayer = $Music++func get_playback_time() -> float:+ # Add time since the last audio mix, subtract output latency, for sub-frame accuracy.+ var t := music.get_playback_position() + AudioServer.get_time_since_last_mix()+ return t - AudioServer.get_output_latency()+```++## Pitfalls++- **Treating volume as linear.** `volume_db`/`set_bus_volume_db` are decibels. Setting+ `volume_db = 0.5` is nearly full volume, not half. Map sliders with `linear_to_db`.+- **`linear_to_db(0.0)` is `-inf`.** Clamp the linear value to a small minimum (e.g.+ `0.0001`) before converting, or special-case 0 → mute.+- **Bus name typos fail quietly.** `get_bus_index("Muisc")` returns `-1`; calls then error+ or no-op. Match the exact bus name from the Audio panel.+- **Short SFX cut off** when the same player is retriggered. Use separate players, an+ `AudioStreamPolyphonic`, or `AudioStreamPlayer` per-shot freed on `finished`.+- **Music doesn't loop** unless the import/stream loop is enabled (`.ogg` import has a+ Loop option; `AudioStreamWAV` has `loop_mode`).+- **Syncing to `get_playback_position()` alone is jittery** — it updates per audio mix,+ not per frame; add `get_time_since_last_mix()` and subtract `get_output_latency()`.+- **3D audio inaudible** → no `AudioListener3D`/`Camera3D` to hear it, or `max_distance`/+ attenuation too tight, or wrong bus muted.++## References++- For the bus layout (`.tres`), adding effects (reverb/compressor/EQ) and side-chain+ ducking, `AudioStreamPolyphonic`/`AudioStreamInteractive`, microphone capture, and+ procedural audio with `AudioStreamGenerator`, read `references/buses-and-effects.md`.++## Related skills++- `audio-design` — engine-agnostic adaptive music, mixing, and ducking practice.+- `godot-animation` — syncing animation/Tween to `get_playback_position()`.+- `godot-ui-control` — volume sliders wired to `AudioServer`.diff --git a/skills/godot/godot-audio/references/buses-and-effects.md b/skills/godot/godot-audio/references/buses-and-effects.mdnew file mode 100644index 0000000..cf89550--- /dev/null+++ b/skills/godot/godot-audio/references/buses-and-effects.md@@ -0,0 +1,86 @@+# Audio buses & effects reference (Godot 4.3+)++Depth companion to `godot-audio`.++## The bus layout++Buses are configured in the editor's **Audio** panel (bottom dock) and saved as a bus+layout resource (`default_bus_layout.tres` by default; set in Project Settings > Audio).++- **Master** always exists and is the final output. Every other bus routes to Master (or+ to another bus via **Send**).+- Add buses like `Music`, `SFX`, `UI`, `Ambience`. Set each player node's `bus` to route.+- Per bus: **volume (dB)**, **mute**, **solo**, **bypass effects**, and a chain of effects.++## AudioServer API++```gdscript+var i := AudioServer.get_bus_index("Music")+AudioServer.set_bus_volume_db(i, linear_to_db(0.8))+AudioServer.set_bus_mute(i, true)+AudioServer.set_bus_solo(i, true)+AudioServer.get_bus_count()+AudioServer.add_bus(at_position) # runtime bus creation+AudioServer.set_bus_send(i, "Master")+AudioServer.add_bus_effect(i, AudioEffectReverb.new())+AudioServer.get_bus_effect(i, effect_idx)+AudioServer.set_bus_effect_enabled(i, effect_idx, false)+AudioServer.get_output_latency()+AudioServer.get_time_since_last_mix()+```++Volume helpers: `linear_to_db(linear)` and `db_to_linear(db)`.++## Effects++Add `AudioEffect*` resources to a bus (editor or `add_bus_effect`):++- `AudioEffectReverb`, `AudioEffectDelay`, `AudioEffectChorus`, `AudioEffectDistortion`.+- `AudioEffectEQ6/EQ10/EQ21`, `AudioEffectLowPassFilter`, `AudioEffectHighPassFilter`.+- `AudioEffectCompressor`, `AudioEffectLimiter` (mastering).+- `AudioEffectPitchShift`, `AudioEffectSpectrumAnalyzer` (for visualizers/beat detection).+- `AudioEffectCapture` / `AudioEffectRecord` (read/record bus output).++## Side-chain ducking (music dips under dialogue/SFX)++1. Put music on a `Music` bus and add an `AudioEffectCompressor` to it.+2. Set the compressor's **Sidechain** to the bus whose loudness should trigger ducking+ (e.g. `Voice`). When `Voice` is loud, the compressor lowers `Music`.+3. Tune threshold/ratio/attack/release for a natural dip and recovery.++## Polyphony and interactive music++- `AudioStreamPolyphonic` — one player that can play many overlapping streams; grab a+ `AudioStreamPlaybackPolyphonic` from `get_stream_playback()` and call `play_stream(...)`.+- `AudioStreamInteractive` — define clips and transitions for adaptive music that switches+ between sections on cue (4.3+). `AudioStreamSynchronized` plays layered stems together.+- `AudioStreamRandomizer` — pick a random stream/pitch per play (great for footsteps).++## Positional audio (2D/3D)++- `AudioStreamPlayer2D`: `max_distance`, `attenuation`, `panning_strength`, `area_mask`.+- `AudioStreamPlayer3D`: `unit_size`, `max_distance`, `attenuation_model`+ (inverse/inverse-square/log/disabled), `panning_strength`, doppler via the player or+ camera. A `Camera3D` acts as the default listener; add an `AudioListener3D` to override.++## Procedural / generated audio++`AudioStreamGenerator` + `AudioStreamGeneratorPlayback.push_frame(Vector2)` lets you push+raw stereo samples for synthesis. Set `mix_rate` and `buffer_length`; keep the buffer+filled in `_process` to avoid underruns.++## Sync-to-beat recipe++```gdscript+const BPM := 120.0+var sec_per_beat := 60.0 / BPM+var last_beat := -1++func _process(_d: float) -> void:+ var t := music.get_playback_position() + AudioServer.get_time_since_last_mix() \+ - AudioServer.get_output_latency()+ var beat := int(t / sec_per_beat)+ if beat != last_beat:+ last_beat = beat+ _on_beat(beat) # spawn, flash, or step a rhythm here+```diff --git a/skills/godot/godot-resources/SKILL.md b/skills/godot/godot-resources/SKILL.mdnew file mode 100644index 0000000..6fd5cb3--- /dev/null+++ b/skills/godot/godot-resources/SKILL.md@@ -0,0 +1,126 @@+---+name: godot-resources+description: >+ Design data-driven Godot 4.x games with custom Resource classes: define typed+ data with class_name + @export, save/load .tres/.res files, instance and duplicate+ resources, and load on demand with ResourceLoader (incl. threaded loading). Use+ when modeling items/stats/configs as data in a Godot project, creating .tres+ resources, or working with custom Resource subclasses and ResourceLoader/ResourceSaver.+license: Apache-2.0+compatibility: Godot 4.3++metadata:+ engine: godot+ category: godot+ difficulty: intermediate+---++# Godot Resources (4.x)++Model game data as reusable, Inspector-editable `Resource` objects instead of hard-coded+values, and load/save them as `.tres`/`.res`. Targets **Godot 4.3+**.++## When to use++- Use when representing items, stats, enemy configs, dialogue lines, or level metadata as+ data; authoring `.tres` files in the Inspector; or loading/saving custom resources.++**When *not* to use:** nodes/scene structure → `godot-nodes-scenes`; saving the player's+*runtime progress* (engine-agnostic save format/slots) → `save-systems`; the C# variant of+this pattern → `godot-csharp`.++## Core workflow++1. **Subclass `Resource`** with `class_name` and `@export` fields. It now appears in the+ "New Resource" dialog and as an `@export` type, editable in the Inspector.+2. **Create instances as `.tres`** files in the FileSystem dock (text, diff-friendly) or+ `.res` (binary, smaller/faster). Edit their fields in the Inspector — no code needed.+3. **Reference resources from nodes** via `@export var data: ItemResource`, or arrays+ `@export var loot: Array[ItemResource]`.+4. **Load at runtime** with `preload` (constant path) or `load`/`ResourceLoader.load`+ (variable path). Use threaded loading for large assets.+5. **Duplicate before mutating** a shared resource at runtime, or every node using it+ changes too (resources are shared references).+6. **Save generated/edited resources** with `ResourceSaver.save`.++## Patterns++### 1. A custom data resource++```gdscript+# item.gd+extends Resource+class_name ItemResource++@export var id: StringName = &""+@export var display_name: String = "Item"+@export_multiline var description: String = ""+@export var icon: Texture2D+@export var max_stack: int = 99+@export var value: int = 0+```++Create `sword.tres` from this class in the FileSystem dock and fill it in the Inspector.++### 2. Consume resources from a node++```gdscript+extends Node+@export var starting_items: Array[ItemResource] = [] # drag .tres files in the Inspector++func _ready() -> void:+ for item in starting_items:+ print("Have: %s (x%d max)" % [item.display_name, item.max_stack])+```++### 3. Duplicate before mutating shared data++```gdscript+func give_unique_copy(template: ItemResource) -> ItemResource:+ # true = deep copy sub-resources too; false = shallow (shares sub-resources).+ var copy: ItemResource = template.duplicate(true)+ copy.value += 5 # mutating the copy won't touch the template .tres+ return copy+```++### 4. Save and load a resource at runtime++```gdscript+func save_config(cfg: Resource) -> void:+ ResourceSaver.save(cfg, "user://config.tres") # user:// = writable app data dir++func load_config() -> Resource:+ if ResourceLoader.exists("user://config.tres"):+ return ResourceLoader.load("user://config.tres")+ return null+```++## Pitfalls++- **Resources are shared by reference.** A single `.tres` assigned to many nodes is the+ *same* object — mutating it changes all of them (and re-saving the file). Call+ `duplicate(true)` for per-instance state.+- **`class_name` required to instance from the editor.** Without it the class won't appear+ in the "New Resource" dialog or as an `@export` type.+- **`res://` is read-only in exported games.** Write runtime data to `user://`, never+ `res://`. `ResourceSaver.save` to `res://` only works in the editor.+- **Storing nodes in a Resource doesn't serialize them.** Resources hold data, not live+ scene nodes. Reference scenes via `PackedScene`, not node instances.+- **Cyclic resource references** (A holds B holds A) can fail to save/load cleanly — keep+ data graphs acyclic or use IDs/lookups.+- **`preload` vs `load`.** `preload` needs a constant path and loads with the script;+ `load` accepts a variable path at runtime. Use `ResourceLoader.exists()` before `load`+ to avoid errors on missing files.+- **Don't put secrets in `.tres`** — they ship in plain text inside the export.++## References++- For threaded/background loading (`load_threaded_request`), `@tool` resources with custom+ setup, custom `ResourceFormatLoader`/`Saver`, resource-local-to-scene, and resource UIDs,+ read `references/resource-patterns.md`.++## Related skills++- `godot-gdscript` — `@export` annotations used to define resource fields.+- `godot-nodes-scenes` — instancing scenes vs. sharing resource data.+- `save-systems` — persisting runtime progress (separate from static data).+- `unity-scriptableobjects` — the equivalent data-asset pattern in Unity.diff --git a/skills/godot/godot-resources/references/resource-patterns.md b/skills/godot/godot-resources/references/resource-patterns.mdnew file mode 100644index 0000000..f201590--- /dev/null+++ b/skills/godot/godot-resources/references/resource-patterns.md@@ -0,0 +1,78 @@+# Resource patterns reference (Godot 4.3+)++Depth companion to `godot-resources`.++## File formats++- `.tres` — text resource. Human-readable, merges/diffs well in version control. Default+ for hand-authored data.+- `.res` — binary resource. Smaller and faster to load; use for large/generated data.+- Convert by re-saving with the desired extension via `ResourceSaver.save`.++## Threaded (background) loading++Avoid frame hitches when loading large scenes/assets:++```gdscript+const PATH := "res://levels/big_level.tscn"++func begin_load() -> void:+ ResourceLoader.load_threaded_request(PATH)++func _process(_delta: float) -> void:+ var progress := []+ match ResourceLoader.load_threaded_get_status(PATH, progress):+ ResourceLoader.THREAD_LOAD_IN_PROGRESS:+ update_bar(progress[0]) # 0.0–1.0+ ResourceLoader.THREAD_LOAD_LOADED:+ var res := ResourceLoader.load_threaded_get(PATH)+ _on_loaded(res)+ ResourceLoader.THREAD_LOAD_FAILED, ResourceLoader.THREAD_LOAD_INVALID_RESOURCE:+ push_error("Load failed")+```++## resource_local_to_scene++By default a `.tres` is shared by every scene that references it. Tick **Local to Scene**+(or set `resource_local_to_scene = true`) so each scene instance gets its own copy at load+time — useful for per-instance materials/state without manual `duplicate()`.++## @tool resources++Add `@tool` to a Resource script to run setup in the editor (e.g. validate fields, derive+values). Guard with `Engine.is_editor_hint()` where needed. Combine with `@export_tool_button`+(4.4+) or a custom inspector plugin for editor actions.++## Custom ResourceFormatLoader / Saver++To load a non-Godot file format as a Resource (e.g. a custom `.deck` text format), register+a `ResourceFormatLoader` (and optionally `ResourceFormatSaver`) and add it with+`ResourceLoader.add_resource_format_loader(loader)`. Override `_get_recognized_extensions`,+`_handles_type`, and `_load`. This lets `load("res://x.deck")` return your resource type.++## Resource UIDs++Godot 4 assigns each imported resource a stable UID (`uid://...`). Scenes can reference by+UID so moving/renaming files doesn't break links. Get one with `ResourceUID`. Prefer+letting the editor manage UIDs; avoid hand-editing `.uid` files.++## Data-driven design tips++- Keep resources **pure data**; put behavior in nodes/systems that read them. This keeps+ data hot-swappable and testable.+- Use `StringName` (`&"id"`) for identifiers/keys — faster comparisons than `String`.+- Model registries (all items, all enemies) as an `Array[YourResource]` exported on an+ autoload, or a directory of `.tres` files loaded at startup.+- A typed export array (`@export var loot: Array[ItemResource]`) enforces element type in+ the Inspector and prevents dragging the wrong resource type.++## Common API++```gdscript+res.duplicate(deep := false) # copy; deep also copies sub-resources+res.take_over_path("res://x.tres")+res.resource_path # where it loaded from ("" if in-memory)+ResourceLoader.exists(path, type_hint := "")+ResourceLoader.load(path, type_hint := "", cache_mode := CACHE_MODE_REUSE)+ResourceSaver.save(res, path, flags := 0) # FLAG_COMPRESS, FLAG_BUNDLE_RESOURCES, ...+```