Topic was automatically imported from the old Question2Answer platform.

Asked By

Lazarwolfe

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?

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.

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