Access variable in a script from another script

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

Hi All, new member here.
I’m trying to add a rpm_meter.tscn scene to a car scene.tscn
The car scene has a body with a script attached for the physics, and i am dragging in also the rpm_meter scene with a script.
In the rpm_meter script i want to call the rpm value to animate a 2d polygon.
I haven’t succeded with direct call nor with a function like so:

rpm variable declared like so in car scene:
export var rpm = 0 setget, rpm_get
Function in car scene script:
func rpm_get():
return rpm

Function call in rpm_meter scene:

To format your code, write it, then select it all and click the “code sample” button. Alternatively, you can write it in another text editor, indent it all by one tab, then copy/paste it.

Zylann | 2020-04-17 12:54

:bust_in_silhouette: Reply From: kidscancode

You’re doing several things wrong here. You don’t need a setget, and even if you did, you’re not using it since you’re trying to call the function instead of accessing the variable (which is what setget is for: calling a function when a variable is accessed).

It’s hard to tell exactly what is happening because of your formatting issues in your post (_ character is for italics in text), but I think I see. You have an instance of a car scene that has another scene as a child, like so:

  |-- RPM_meter

When you use get_node(), you use node names not filenames. car.tscn is a filename - it’s where the scene is saved but has nothing to do with the node running in the live game. Since the car is the parent, you can use get_parent():


Keep in mind, this will not work if it’s in the child’s _ready() function, because child nodes become ready before parents.

Accessing nodes is frequently misunderstood by beginners. The following might help you avoid some of the common errors:

Thanks a lot. Wasn’t aware of the kidscancode resource. Will use it a lot. Will try to fix the problem right now (my lack of knowledge problem).

Streetslab | 2020-04-18 19:44