How to access variable of script of a node?

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

Hello I have a script on my camera and a target variable in that script which I’ve exported. I am trying to access the variable from the player script and it doesn’t work. Here’s the code in the player script:

var camera
var hextor

hextor = get_tree().get_root().get_node("Stage").find_node("Hextor")
camera = get_tree().get_root().get_node("Stage").find_node("Camera") = hextor

I get an invalid index error. What am I doing wrong?

The exact error:

Invalid set index 'target' (on base: 'Camera2D') with value of type 'KinematicBody2D ('.

How does the script on your Camera2D look like? Do you only have one Camera2D-node or multiple ones? Are you sure the script is attached and the variable is named target? The error tells you that you’re accessing an index of your Camera2D-node which doesn’t exist - either because the script does not exist or the variable is named differently. The code you provided looks correct - I cannot reproduce the issue!

njamster | 2020-03-25 23:28

:bust_in_silhouette: Reply From: Sween123

If I remembered correctly, back in time when I just started using Godot (older version), Using NODE.VARIABLE won’t work.
Try use function set()
For example:

camera.set("target", hextor)

To get the variable, use function get()

If that’s not the case, it’s also likely that it’s because in node camera you didn’t define the variable target. So before you get or assign a value to it, make sure in the script attached to camera, you have something like var target

node.variable should definitely work as long as the node reference exists (i.e. it’s not null) and the property exists in the node.

That said, set()/get() are still useful to set/get properties based on dynamic names with a gracefull fallback (it won’t crash if the property doesn’t exist).

Calinou | 2020-03-27 08:23