This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

So, I have two nodes that hold an equal amount of children each; each node has a timer connected to it as well, which triggers on a random timer ranging from 1 to 3.

How would you folks iterate both arrays at the same time independently from each other each time the timer emitted timeout without getting an out of index error?

in Engine by (27 points)

1 Answer

+1 vote

Next time, please share your script. It'll make it easier for you and for us.

Let's say you've got your manager which handles the iteration logic. It's children are these two node you want to swap.

onready var current_node = $Node1
onready var next_node = $Node2
var current_index = 0

function iterate():
    # the percent sign is called the modulo operator.
    # https://en.wikipedia.org/wiki/Modulo_operation
    var child = current_node.get_child(current_index % current_node.get_child_count())
    current_index += 1
    child.do_stuff()

function swap_node(): # called on timer timeout
    var temp = current_node
    current_node = next_node
    next_node = temp

The benefit of the modulo operation is that you'll never get a index out of bounds error (unless the node has no children...) and you don't need to set it back to zero once you've reached the end. It also means that the nodes can have a different number of children.

However, since both nodes share the same index, you'll skip over some children. I don't know if that's what you want. If not, just keep two indices and swap them out in swap_node.

by (1,254 points)

Thanks! I keep forgetting how useful modular arithmetic is when iterating!
Will share code next time, sorry for the hassle.

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.