Accessing and changing variable from another node's script

Godot Version

Godot 4

Question

Hey, so I’m trying to access the “health” variable which is in my “player” script in another node’s script which is “damagetrigger”. So basically I want to decrease the health of the player from the damagetrigger node by decreasing “damageamount” from the player’s health, but I can’t seem to get the health of the player in the damagetrigger script even though I tried to find a solution still none really worked for me. Any help is appreciated.

What solutions have you tried?

Posting example code will help us identify any issues and suggest solutions for your specific code. (Use ctrl+e to format the code neatly).

A generic example of updating a property in the other script:

damagetrigger.gd

@onready var player = $Player
var damageamount: int = 10

func damage():
    player.hit(damageamount)

Player.gd

var health: int = 100

func hit(amount):
    health -= amount

Hey there! I think I may have a solution for you. It seems like the problem is in your “damagetrigger” script. You can actually access the “health” variable from the “player” script by using the following code:

#damagetrigger script
extends Node2D

func _on_Area2D_body_entered(body):
if body.name == “player”:
var player = body
if “health” in player:
player.health -= damageamount


In this code, we are checking if the object that entered the trigger area is the player. If it is, we then access the player's "health" variable and decrease it by the "damageamount" as you intended.

Just a reminder that its good practise to replace "Area2D" with the actual name of the area node that represents your damagetrigger. Also, make sure that "damageamount" is defined in the damagetrigger script or is accessible from it. I hope this helps! Let me know if you have any questions.

Hey, thanks a lot for the effort! Sadly I have an error in which the code doesnt recognize the “player” in the line “var player = body”, so I created an onready variable for the player, but it still doesn’t work. Is there a way you can show me to get around this? Thanks.

Hey! I tried it but like in my original problem the code can’t detect damageamount from the player script. Is there a solution to that?

Yes. The solution depends on the cause though.

Could you post the relevant code sections, a screenshot of your node tree and of course the error message you are getting so we can identify the problem?

Without this info we can only guess at possible solutions to a problem hidden from us.