can't access the functions of another node scripts

Godot Version

Godot_v4.5-stable_mono_win64

Question

(my code is all in c#) in the following video, inside the melee() function the man accesses the variable "health" with "body.health". but when i try to do the same thing in my code it doesn't allow me to get to that variable or to be more specific, nothing inside the class that the script has

this is the main part.

public override void _Process(double delta)
	{
		base._Process(delta);
		if (Input.IsActionJustPressed("attack") == true)
		{
			if (!WeaponAnimation.IsPlaying())
		{
			WeaponAnimation.Play("attack");
			WeaponAnimation.Queue("return");
		}
		if (WeaponAnimation.CurrentAnimation == "attack")
		{
			foreach (var enemy in WeaponHitbox.GetOverlappingBodies())
			{
				MeshInstance3D parent = enemy.GetParent<MeshInstance3D>();

					if (parent.IsInGroup("enemy"))
					{
						GD.Print(enemy.Name);
						GD.Print(parent.Name);
						//parent.gothit()
						
				
				}
			}
		}
		}
		
    }

this is what the two GD.Print() print
image

this is the enemy code:

using Godot;
using System;

public partial class Enemy : MeshInstance3D
{
	public float healthShi = 10.0f;

	public void gothit(float DamageGotten)
	{
		healthShi = -DamageGotten;
	}
	public override void _Process(double delta)
	{
		if (healthShi <= 0)
		{
			QueueFree();
		}
		
	}
}

i can answer fairly quickly for the next like, 2 hours i guess

Hi,

In your current context, parent is of type MeshInstance3D which indeed does not contain the gothit method. C# has no idea that the node is actually a Enemy, which is a subclass of MeshInstance3D, so you have to tell it yourself, like this:

(parent as Enemy).gothit(damage);

or

((Enemy)parent).gothit(damage);

This is called “casting”. Let me know if you need more info on what that code does exactly, but that should work fine.


Another way of fixing your code is to directly access the parent as an Enemy, by changing that line:

MeshInstance3D parent = enemy.GetParent<MeshInstance3D>();

to:

Enemy parent = enemy.GetParent<Enemy>();

And you should then be able to access the gothit method, since the code now knows the node is an Enemy.

Thank you! this solution was the one that fit me and it worked without problems!

1 Like