+1 vote

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")
camera.target = 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 (player.gd)'.
in Engine by (34 points)

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!

1 Answer

0 votes

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

by (805 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.