|Topic was automatically imported from the old Question2Answer platform.
I have 2 questions and I started with Godot a few days ago.
How can I transfer a variable from one script into another script? The only similarity of those scripts is that they have the same Rootnode.
How can I get the position of a KinematicBody2D in a another Node? The only similarity of those Nodes is also that they have the same Rootnode.
Thanks for answer!
PS: Sorry for bad English I am a Student from Germany .
PPS: Sorry if you see my question twice, I am new with this website and it is posible that I send the question twice.
By using a singletons and creating a global variable. More on that here.
Singletons (AutoLoad) — Godot Engine (3.1) documentation in English
Or if possible you can utilize signals because in some cases for example a signal can tell another script if something has changed about the variable.
If you are trying to set a nodes position to another nodes position then once again you can store the node’s position into a singleton and call it in any script that you want.
You can also get position with $Node.position
You need to get a reference to the node which contains the variable. Since both nodes share the same root, you could reference that root node and then grab the variable in question.
So, for the sake of clarity, let’s name those nodes as follows:
Now let’s say you have a script on
Foo and another one on
Foo has a variable
bob = 'I am Bob'. Now you want to write code in
Bar’s script which will get you the value of
Foo. You write this in
var f_bob = get_parent().get_node("Foo").bob
See what we did there? we referenced the common rootnode (
Rooty in our case), then we found the
Foo node and then we got its
bob variable which we stored in another variable named
This sounds logic. But i tried it exactly as you discribted, but obviously I made it wrong. The error sounds like this:
Attemp to call function “get_node” in base “null instance” on a null instance
Do you know what I made wrong? I do not understand how I can add a Screenshot to this. If you tell me how this works, I can send a screenshot, too.
Godot_Starter | 2020-01-05 16:30
Ok my bad! It should have been:
onready var f_bob = get_parent().get_node("Foo").bob
This error occurred because the node you were trying to reference had not yet been instanced. That is why we use the
onready keyword, so that Godot knows to reference the object after it has been instanced
johnygames | 2020-01-05 23:02