Search code examples
godot

How can i export a var with specific class


I want to export a HealthComponent

extends Node2D
class_name HealthComponent

in HitComponent node I tried 2 ways:

export var HealthComponent: Node2D

and

export var HealthComponent: HealthComponent

and it gives me this error: an error

note: my version is v3.5.2.stable


Solution

  • You can do it this way:

    export(NodePath) var HealthComponentPath
    
    onready var HealthComponent = get_node(HealthComponentPath)
    

    Here is Godot 3.5 export documentation. It says:

    An exported variable must be initialized to a constant expression or have an export hint in the form of an argument to the export keyword (see the Examples section below).

    What it means is you can use either form, initializing with a constant expression

    export var <Name> = <constant expr.>
    

    or using export(<RecourceType>) syntax. But both ways Godot 3 requires variable to be of a built-in or native resource type, and Node2D is not.

    # If the exported value assigns a constant or constant expression, the type will be inferred and used in the editor.

    export var number = 5

    # Export can take a basic data type as an argument, which will be used in the editor.

    export(int) var number

    # Export can also take a resource type to use as a hint.

    ...

    Godot 4 added possibility to do that directly, but old syntax like this is also supported there.

    Since Godot 4.0, nodes can be directly exported as properties in a script without having to use NodePaths. ... Exporting NodePaths like in Godot 3.x is still possible.