The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

+1 vote

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?

in Engine by (16 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

+2 votes
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.

by (29,360 points)
selected by
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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.