How do I access a script attached on a colllider I hit with a raycast from another script?

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

A physics object has a raycast that hits the environment to get information from scripts attached to the environment’s colliders.

How do I get references to those scripts from the script on the physics object? I can get a reference to the collider itself, but how do I get a reference to the script attached to it and to variables in it?

Are you using signals? They would be very useful for this.

ejricketts | 2021-01-17 18:12

No, because I’m not always interacting with the same node and I would have to retrieve the correct nodepath every time.

Unityfugee | 2021-01-17 20:52

So if the objects you are interacting with are saved as a scene, then you can set up a signal within the script on that scene and all of the instances of it in your game will have the signal set up

ejricketts | 2021-01-17 21:05

:bust_in_silhouette: Reply From: Wakatta

To get the script attached to a node simply use get_script() on that nodes instance

Before i go any further know that collider to which you obtain a reference must be a CollisionObject or Inherited form of.

So if a script is not attached to it then you’ll want to use that instance to get the node that does have the script attached

"To get the script attached to a node simply use get_script() on that nodes instance"

That returns the script as if loaded from a NodePath but having that information is probably not what you want as you cant access a members variables using that.

The collider you get from the rayCast using for example $RayCast.get_collider() is the actual instance you want and to access its variables just use $RayCast.get_collider().variable assuming you have a valid collision of course

enter image description here

var speed = 1
var enemies = Array()

In the image above My Agent node has script attached, notice that all variables defined in become members of the Agent node instance

The Mesh node child of Target also has the same script attached so if i did a rayCast i’d get the Target node since it is the CollisionObject, so to get the members

var node = $RayCast.get_collider()
if node: node.get_child("Mesh").speed = 4