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


in Engine by (88 points)
edited by

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")
by (3,350 points)
selected by

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.

by (181 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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.