How to access a script of another node whose parents have different names?

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

So I want to make it so that when the player picks up a weapon, he switches to a player “holding weapon” - animation, and to do that the player script needs to access the “PickupWeapon” - script, since it holds the “isHolding” - variable. The problem is that the PickupArea node, which also has the PickupWeapon script, is instantiated as a child to the weapons I have and they have different names, which makes it so that I can’t access the script through them.

The main scene tree looks like this:

Player[Player script attached]


PickupArea[Pickup Script attached]


PickupArea[Pickup Script attached]

So basically as the title says, how can I get the “PickupWeapon” - script, from the player-script, if the PickupArea’s parents have different names?

:bust_in_silhouette: Reply From: Wakatta

So you could move the Pickup area to be the parents with the names of the weapons like this

   ┠╴Pistol (Area) [Pickup Script]
   ┃  ┖╴PistolMesh
   ┖╴Sniper (Area) [Pickup Script]

Or get the reference child of the weapons through iteration

func get_ref():
    for child in $Pistol.get_children():
        if "isHolding" in child:
            return child

Even better if your script has a pickup function you could do something like if child. has_method(pickup)

Ok so if im going for the first method, what should I write in the player script to get the PickupScript?

Because I cant write:


Because that will only allow me to change the player pickup-animation on the pistol, and not on the sniper.

LyguN | 2021-07-01 20:14

┖╴Player[Player script]
   ┖╴Sniper (Area) [Pickup Scrip]

With your setup like this, you’ll still have to use this instead from your player script

for child in get_children():
    if "isHolding" in child:

And the child reference will be the first node with the pickup script attached

The beauty in putting the script in the Area as the parent is that after you’ve called add_child($Pistol) you can call move_child($Pistol, 0) so your weapon will always be the first child and you can call get_child(0) since you’ll know where your weapon is located in the sceneTree

Wakatta | 2021-07-02 16:45