Reuse custom resources
This example shows how to create a custom resource and reuse it with different settings.
1. Create custom resource
We create a new file character-attributes.ts
and add this code to it:
character-attributes.ts
import { Export } from "godot.annotations";
import { Resource, Variant } from "godot";
export default class CharacterAttributes extends Resource {
@Export(Variant.Type.TYPE_INT)
health: number = 5;
}
2. Create new resources
- Left-click on the
res://
folder in the file system. - Select
➕ Create New > 📦 Resource
- Search for
CharacterAttributes
and select it. - Save the resource as
warrior.tres
- Repeat the process and save it as
mage.tres
- Change the
health
property to8
for thewarrior.tres
resource
3. Create a GodotJS class to consume the resources
Create a new file index.ts
and add this code to it:
index.ts
import { Node, Variant } from "godot";
import { Export } from "godot.annotations";
import CharacterAttributes from "./character-attributes";
export default class ResourceExample extends Node {
@Export(Variant.Type.TYPE_OBJECT)
warriorAttributes: CharacterAttributes | undefined = undefined;
@Export(Variant.Type.TYPE_OBJECT)
mageAttributes: CharacterAttributes | undefined = undefined;
_ready(): void {
console.log("warrior health", this.warriorAttributes?.health);
console.log("mage health", this.mageAttributes?.health);
}
}
4. Create a node and add ResourceExample
- Create a new scene and add a
Node
as root node. - Attach the
index.ts
script to the root node. - Select the root node and add the
warrior.tres
andmage.tres
resources to the properties. You can drag and drop the resources from the file system into the properties. - Run the project and check the output in the console.