How to access nodes of a node added to another node in code?

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

I have a KinematicBody2d based player character and want to add items, like weapons, etc. to the character. Currently I’m doing:

current_weapon = preload("path to weapon.tscn").instance()
add_child(current_weapon)

This works fine and add the weapon instance as expected. However each weapon also has multiple animations that should be played based on the character’s state and I can’t find a way to access the weapon’s AnimationPlayer node from the player character script. I’ve tried:

weapon_anim_player = current_weapon.get_node("AnimationPlayer")

But when I try to play the animations, nothing plays.

:bust_in_silhouette: Reply From: Diet Estus

Not sure why that’s happening for you…

But you can try creating an animation_player variable in the weapon script.

In weapon script:

onready var animation_player = get_node("AnimationPlayer")

Then, when you reference the weapon from your player script, you can just call this variable which belongs to the weapon.

In player script:

if state == "Shooting":
    current_weapon.animation_player.play("Fire")

It turned out I was just doing something dumb in the code that set which animation was playing, but thank you very much for the answer, I appreciate it.

Socrates | 2018-04-07 03:37

No worries. I do dumb stuff all the time.

Diet Estus | 2018-04-07 03:42