0 votes

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.getchildcount()):
$Heroes.get_child(i).Sprite.texture = load("res://Sprites/Archer.png")

Editor says "Invalid get index 'Sprite' (on base: Node2D')."


asked Jan 16 in Engine by Fenisto (40 points)
edited 5 days ago by Fenisto

2 Answers

+2 votes
Best answer

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")
answered Jan 16 by wombatstampede (2,785 points)
selected Jan 16 by Fenisto

Should have done it sooner.
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.

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")

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

0 votes

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":

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

answered Jan 16 by eod (92 points)

Sorry, same thing as the previous answer.

Need to get "Heroes\Hero\Sprite.texture". Not "Heroes\Sprite"

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.