How to get the node name that raycast2d collided with?

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

I need help with getting the node the raycast collided with. Before i used a string that contained the collision id of the node, but the id changes everytime i boot up the project. And the only thing i could do to make the results more reliable would be getting the node name. Is there anyway i can do this?

:bust_in_silhouette: Reply From: rustyStriker

You can use get_collider() , it returns the object the ray is colliding with and you can extract it’s name using var.name property…

just make sure to add a safe guard in case the ray doesn’t collide with anything

GetCollider() returns Godot.Object which does not contain a definition for Name.

Dayls | 2021-06-08 07:49

If you are using C#(never used it with Godot) you might need to cast the object to a node or other class to be able to get all the relevant data

rustyStriker | 2021-06-08 08:35

:bust_in_silhouette: Reply From: kennychidot

Use get_collider() which returns the first object that rayCast2D collides with be it an area2D or a body depending on your preferred presets. You can then use to_string() to get the name of the object, ensure to check if the result from get_collider() is not null. You can use this feature to ensures enemies do not see through walls.