#Node not found when trying to access a child node from another parent node

1 messages · Page 1 of 1 (latest)

lunar dock
#

I have Bat enemy, I want its health decrease when player's Hitbox enter Bat's Hurtbox.

Bat.cs:

`public class Bat : KinematicBody2D
{
private const float KNOCKBACK_FORCE = 120;
private Vector2 knockback = Vector2.Zero;
private Stats stats;
public SwordHitbox swordHitbox;

public override void _Ready()
{
    stats = (Stats)GetNode("Stats");
    swordHitbox = (SwordHitbox)GetParent().GetNode("/root/scenes/Player/SwordHitbox");
}
public override void _PhysicsProcess(float delta)
{
    knockback = knockback.MoveToward(Vector2.Zero, delta * 200);
    knockback = MoveAndSlide(knockback);
}
private void onHurtBoxAreaEntered(Area2D area)
{
    var pivot = area.GetParent();
    var player = (Player)pivot.GetParent();

    stats.Health -= swordHitbox.damage; // ERROR Node not found
    
    knockback = player.rollVector * KNOCKBACK_FORCE; // player.rollVector: Get the direction player is facing and make it knockback direction.
}

private void onStatsNoHealth()
{
    QueueFree();
}

}`

The player.tscn node look like this:

Player
|-- ...
|-- HitboxPivot (Type: Posittion2D)
|-- SwordHitbox (Type: Area2D)
|-- CollisionShap2D

Continue in next message...

#

The SwordHitbox have script attached and inherits from Hitbox:

SwordHitbox.cs:
public class SwordHitbox : Hitbox { public Vector2 knockbackVector = Vector2.Zero; }

Hitbox.cs:
public class Hitbox : Area2D { [Export] public int damage = 1; }

Error appear on runtime when the Player hit the Bat:

E 0:00:00.984 get_node: (Node not found: "root/scenes/Player/SwordHitbox" (relative to "/root/Game/Bat").) <C++ Error> Method failed. Returning: nullptr <C++ Source> scene/main/node.cpp:1476 @ get_node() <Stack Trace> :0 @ Godot.Node Godot.NativeCalls.godot_icall_1_673(IntPtr , IntPtr , IntPtr )() Node.cs:685 @ Godot.Node Godot.Node.GetNode(Godot.NodePath )() Bat.cs:14 @ void Bat._Ready()()

E 0:00:04.014 void Bat.onHurtBoxAreaEntered(Godot.Area2D ): System.NullReferenceException: Object reference not set to an instance of an object. <C++ Error> Unhandled exception <C++ Source> D:\Godot_v3.5.3-stable_mono_win64\Workspace\GenericRPG\scripts\Enemies\Bat.cs:26 @ void Bat.onHurtBoxAreaEntered(Godot.Area2D )() <Stack Trace> Bat.cs:26 @ void Bat.onHurtBoxAreaEntered(Godot.Area2D )()

Please point me what did I do wrong here, thanks.

lunar dock
#

After few hours of trial and error, I found out the answer to my question. I changed this line

swordHitbox = (SwordHitbox)GetParent().GetNode("/root/scenes/Player/SwordHitbox");

To this
swordHitbox = (SwordHitbox)GetNode("/root/Game/YSort/Player/HitboxPivot/SwordHitbox");

I used the GD.Print(GetPath()); to get the path of SwordHitbox.

Look unmaintainable but it don't cause error this time. Anyone have better approach would be very appreciated.