Access Variable from other script in c#

Godot Version



I have 2 scripts in c# the one is called hero.cs attached to CharacterBody2D it contains the variable
public int Health = 100;
The other script is called fireball.cs it’s attached to area2d I m using the body entered signal to check if the ball collides with player and if it does I want to change the Health variable from fireball script

public override void _Ready()
BodyEntered += On_Collision;

public void On_Collision(Node2D Other_Body) {
if(Other_Body.IsInGroup(“Player”)) {
//reduce health of player
Other_Body.Health-= 50;
Print(“Collision with Player”);
It doesn’t work godot tells me CS1061: ‘Node2D’ does not contain a definition for ‘Health’ and no accessible extension method ‘Health’ accepting a first argument of type ‘Node2D’ could be found (are you missing a using directive or an assembly reference?) /home/kim/Fantasy_Adventure_Game/Code/Enemies/Red_Dragon/fire_ball.cs(24,21)

You need to cast your reference on Other_Body to its concrete type (which would be hero here). One way would be to use pattern matching:

if (Other_body is hero hero_body)
    hero_body.Health -= 50;

Or you can simply use a cast:

// This is going to throw an exception if Other_body isn't of type hero.
var hero_body = (hero)Other_body;
hero_body.Health -= 50;
1 Like