Variables and Positions. (Starter Question, so for you very easy to answer :) )

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

I have 2 questions and I started with Godot a few days ago.

  1. Question:
    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.

  2. Question:
    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 :slight_smile: .
PPS: Sorry if you see my question twice, I am new with this website and it is posible that I send the question twice.

:bust_in_silhouette: Reply From: Asthmar
  1. 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.

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

:bust_in_silhouette: Reply From: johnygames

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:

-Rooty
–Foo
–Bar

Now let’s say you have a script on Foo and another one on Bar. 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 bob in Foo. You write this in Bar’s script:

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 f_bob

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