0 votes

If I try to preload this GDscript, then everything is fine:


But if I replace Gdscript with VS script:


Why .new() not working here? How to get variables in this case?

asked May 7 in Engine by Trentmast01 (15 points)

Unrelated, but FYI the GDScript preload example you posted is more than just preloading, it also shows creating an instance of it, which is rarely necessary and the variable won't be shared in places you do this anyways. If the script defines const members and static functions for example, in this case new is not required (specific to GDScript).

1 Answer

+1 vote
Best answer

Perhaps the real problem here is how to create an instance of a VisualScript. Note that new does not really mean "you can access variables", it means a new instance of the script is being created. Each instance is independent from others.

When you use new in GDScript, what it does is to create an instance of the class it extends from, and hen attach an instance of the script to it. This looks transparent from script usage, but that's what actually happens under the hood.

new doesn't seem to work with VisualScript. So you'll have to use what's under the hood manually:

func _ready():
    # If the script extends `Node`, create a new node. 
    # If it extends something else, change the class.
    var node = Node.new()

    # This creates an instance of the script
    node.set_script(preload("visual.vs")) 

    print(node.TEXT1)

This works for me.
Also verify what class your VisualScript extends from. If it's a node, it must be added to the tree because otherwise it will leak when not freed manually.

answered May 7 by Zylann (26,787 points)
selected May 7 by Trentmast01
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.