3
\$\begingroup\$

I'm going through the "Creating your own resources" steps. Here's an abbreviated version of the demo resource bot_stats.tres and the associated bot_stats.gd script:

extends Resource

@export var health: int

func _init(p_health = 0):
    health = p_health

And they suggest using it like this in another Node:

extends CharacterBody3D

@export var stats: Resource

func _ready():
    # Uses an implicit, duck-typed interface for any 'health'-compatible resources.
    if stats:
        stats.health = 10
        print(stats.health) # Prints "10"

Is it possibly to use a stronger type-hint? I'd love to have (and tried) something like:

@export var stats: BotStats

or

@export var stats: bot_stats

To get some intellisense rolling in the editor. But they give things like:

Error at (3,18): Could not find type "BotStats" in the current scope.

Is this possible?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You need to give a class name to your custom Resource first. For example:

class_name BotStats
extends Resource

@export var health: int

func _init(p_health = 0):
    health = p_health

Then you should will be able to use that on the export variable:

@export var stats: BotStats

See Static typing in GDScript, Registering named classes and the Resources section of GDScript exports.

By the way, even though the term "type hint" stuck, these are actual type definitions, not just hints.

I also want to mention that this is not implemented properly in Godot 3.x at the time of writing (see pull request 44879), there are workaround, but since you are for Godot 4, I'll not get into that. We can consider this a Godot 4 feature.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .