How do I access a node through it's index?

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

I’m trying to parse through a node’s children and get their indexes. Which is successful with get_child().
Then i’m trying to access every child’s child which is a sprite and change it’s texture value. But it doesn’t seems to work.

For example:
for i in range($Heroes.get_child_count()):
$Heroes.get_child(i).Sprite.texture = load(“res://Sprites/Archer.png”)

Editor says “Invalid get index ‘Sprite’ (on base: Node2D’).”

Tree

:bust_in_silhouette: Reply From: wombatstampede

That code (if corrected) will only work when all childs of the Hero are Sprites.

The correction would be to remove the “.Sprite”.

for i in range($Heroes.getchildcount()):
   $Heroes.get_child(i).texture = load("res://Sprites/Archer.png")

You can also check if the child is actually a Sprite:

for i in range($Heroes.getchildcount()):
   if $Heroes.get_child(i) is Sprite:
      $Heroes.get_child(i).texture = load("res://Sprites/Archer.png")

If the child node has i.e. the Name “MySpritê” you can adress it also via the node path:

$"Heroes/MySprite".texture = load("res://Sprites/Archer.png")

Should have done it sooner.
Tree

The point is to access Hero1, Hero2 etc. nodes, and their sprite nodes. And change sprite.texture of every Hero* on a go.

Your suggestion is if there is only “Heroes” node that has a bunch of sprites.

Fenisto | 2020-01-16 10:43

As far as I know get_children() and get_child() will get only the direct children (opposed to find_node()). So it doesn’t recurse.

You could do it this way:

for i in range($Heroes.get_child_count()):
   var spr = $Heroes.get_child(i).get_node("Sprite")
   if spr != null:
      spr.texture = load("res://Sprites/Archer.png")

wombatstampede | 2020-01-16 11:30

$Heroes.get_child(i).get_node("Sprite")

This is just what I were looking for. Thank you.

Fenisto | 2020-01-16 11:50

:bust_in_silhouette: Reply From: eod

Does this work?

var hero_child_node_arr:Array = $Heroes.get_children()

for i in range(hero_child_node_arr.size()):
    if hero_child_node_arr[i].get_class() == "Sprite":
        hero_child_node_arr[i].set_texture(load("res://Sprites/Archer.png"))

The idea is that you need to check if the child node is a Sprite first, then if it is, set the texture.

Sorry, same thing as the previous answer.

Tree

Need to get “Heroes\Hero*\Sprite.texture”. Not “Heroes\Sprite*”

Fenisto | 2020-01-16 10:50