How can I get Node type/instance for a Godot Object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By miivers

Lets say I shoot a bullet in my game and does a raycast in order to check if I hit an enemy or not. If I hit an enemy I want to subtract its health by some value. Raycast get_colider returns an Object to the Body or Area we cast into. So I now have an object. What do I need to do in order to get the script I have attached to the enemy I have raycasted into?

:bust_in_silhouette: Reply From: AlexTheRegent

You can use get_parent or get_node("..") to get direct parent. You can also use get_owner to get parent of whole instanced scene. So if you have next scene:

parent
     child1
          child2
               child3

child3.get_parent() will return child2 and child3.get_owner will return parent.

In C# methods should have GetParent and GetOwner names.

I think I might have fund my answer while making some code to make my question a bit more clear. My initial question was about going from an Godot.Object to the type I wanted to interact with. For some reason it took me a while to realize I could just cast directly to it…

public override void _PhysicsProcess(float delta)
{
    UpdateCastToPosition();
    Godot.Object result = rayCast.GetCollider();

    if (result != null)
    {
        GD.Print($"Hit at position {rayCast.GetCollisionPoint().ToString()}");

        if (result is StaticBody staticBody)
        {
            GD.Print($"{staticBody.Name}");
            if(staticBody.GetParent() is Test test)
            {
                GD.Print($"Found Test script");
            }
        }
    }
}

miivers | 2021-01-08 23:27