Changing a variable from another script

Godot Version

4.1.2

Question

How can I change the value of a variable from another script?
I have two scripts named Player.gd and Button.gd. I’m trying to change the value of the variable health from the Player script by pressing the button.
This is what i wrote:

Player.gd:

extends Sprite2D

var health = 4

Button.gd:

extends Button

var player = preload("res://Player.gd")

func _pressed():
	player = player.new()
	player.health += 1

The button functions normally but the value doesn’t change at all.

You are making a new instance of a script in the player var. What you want to do, I am guessing, is to reach the player object (on some other node - which has player.gd attached to it). You would use node path references for this.

Maybe post your scene tree (a screenshot).

1 Like

I just have a node named Player and a button named Button with the scripts attached to each of them. could you explain a little bit more? thanks.

Assuming your tree looks something like this:

|-player (player.gd)
|
|-button (button.gd)

Then, change your script like:

extends Button

@onready var player = $player

func _pressed():
  player.health += 1
  print("player health is:", player.health)
1 Like

it told me to use @onready before var player = $player and i got an error:

invalid get index ‘health’ (on base: ‘null instance’)

I edited my last post. Try that.

Posting a screeny of your scene tree would help.

as i said, i already did. it also gave me this:
Button.gd:3 @ _ready(): Node not found: “player” (relative to “/root/Node2D/Button”).

I don’t realy know what the scene tree is but here you go:

Try @onready var player = $"../Player"
You can drag & drop the Player node into the code editor while holding CTRL to create that line automatically.

2 Likes

Ah, you spell Player with a capital P. Gdscript is case-sensitive, so switch to:
@export var player = $Player

1 Like

It worked. Thank you both so much!

2 Likes