0 votes

I have Object1 of type Area2D and Object2 of type Area2D.

Object1 has the following function (attached to a signal area_entered(area; Area2D):

# This function handles collisions between objects (Area2Ds)
func bounce_from_area(var who):
    hit_object = who

now hit_object is a global variable in Object1. So whenever Object2 (Area2D) collides with my Object1, Object1 stores the collided object in hit_object variable.

So let's say Object1 was hit by Object2. Now Object1.hit_object stores Area2D object. If I use hit_object.name I would get "Object2" name). All is fine up to this point.

Now I'd like to get to the child of Object2 stored in hit_object variable. But I can't.

The below code doesn't work:

var temp1 = hit_object.AnimatedSprite.animation

I get the following error:

Invalid get index 'AnimatedSprite' (on base: 'Area2D (Objectr1.gd)').
in Engine by (23 points)
edited by

1 Answer

+1 vote
Best answer

Hi,
you need to use get_node()

var temp1 = hit_object.get_node("AnimatedSprite").current_animation
by (4,010 points)
selected by

Yes, it's working! Thank you!

Can you explain why it's working?

I mean, intuitively I wanted to use:

var temp1 = who.AnimatedSprite.animation

but it reports error about Area2D node.

The below code is working:

temp1 = who.get_node("AnimatedSprite").animation

I often use dot notation to refer to child nodes, but this time I need to use get_node(), why?

Child nodes are not class members, they are managed through the scenen tree.
When you use the dot syntax you try to access a class member.

Get_node gets child nodes from the scenen tree using a nodePath.

You should check the docs for NodePath, its an essential part of working with godot.
https://docs.godotengine.org/en/stable/classes/class_node.html#class-node-method-get-node

Thank you! All is clear now.

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 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 webmaster@godotengine.org with your username.