This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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?

Godot version Godot Engine v3.2.3.stable.mono.official
in Engine by (36 points)

1 Answer

0 votes

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.

by (1,656 points)

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");
            }
        }
    }
}
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.