How to access a variable inside VS script via GDscript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Trentmast01

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?

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).

Zylann | 2020-05-07 13:27

:bust_in_silhouette: Reply From: Zylann

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 =

	# This creates an instance of the script


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.