I am making a save system for my game. I have the save system get up, but I am trying to access a variable in my player script in another script. How do? I tried something like:

onready var nextLevel = get_tree().get_root().get_node("Node2D).find_node('Player_Node) (or just Player_Node in the get_node()

then in a function I tried

nextLevel.level += 1

But it doesn't work.

How do?

Variables are public by default, so you just have to use get_node to access the node, and then add a dot and then the variable name. You can see my post here for getting nodes. https://godotforums.org/discussion/comment/30926/#Comment_30926

You can do something like this:

 onready var playerNode =  get_node("/root/Scene/Node2D/Player_Node")

Then later, read or alter the level variable:

playerNode.level += 1
print("level: ", playerNode.level)

Make sure you access the variable through the node, so it is actually updated. If you just save the level in a variable, that becomes a new integer variable (not associated with the player node) and when you add to it, you are only adding to the copy, not the original value.

Hope that helps.

I've tried that, I get "Invalid get index 'level' ( on base: 'null instance').

The error seems to be that the object that you are trying to access the variable in is null. In other words, the error is saying that playerNode is null. I would double check your NodePath in get_node and maybe add print(playerNode) to make sure the get_node call is returning the node you want.

Okay it's detecting the node now. But when I do:

print(nextLevel.level) ((The .level coming from the player script which has a variable named level) I get the following error.

Invalid get index 'level'(on base: 'Node2D').

When I print nextLevel, it gives me no errors, but when I try to use the variable from the other script, I get errors.

Most likely, your node path is not actually getting the script with the level on it. Double check that it is the correct node, and that the value you are trying to reach is declared at the top of the script (meaning not within a function, as that will be a local variable and not accessible outside that function).

I bring in my player from another scene each level, could that be the reason? If so, how would I path it correctly?

6 days later

If you are instantiating the player with code, it's possible that onready (or _ready) is being called before the player is added to the tree. It would be good to not initialize the player/level variable until after this is complete.

Also, make sure the script is on the first node inside the player scene (not on the outside on the player instance).

3 years later