Learn

Chapter 03 Conditions, Time & Loops

#029 For Each Loop

One frost spell. Every enemy in range. Not four copied graphs, just one For Each Loop.

  • 1:12 video
  • Written lesson
  • Beginner
Video lesson: For Each Loop, 1:12

The array itself, not indexes

A For Loop needs a First and Last Index. For Each Loop takes the array itself: plug any array into its Array pin.

Loop Body fires once per item, from index zero up to the last one. Array Element is the current item, and Array Index is its position. So you don’t need a Get node here: Array Element already holds the item, and Array Index starts at zero.

After the last item, Completed fires once. An empty array skips Loop Body and goes straight to Completed.

Example: a frost spell

Enemies In Range holds four enemies. Loop Body calls Freeze, with Array Element as the Target.

Enemy 0, enemy 1, enemy 2, enemy 3. Each enemy is frozen exactly once, and then Completed fires. In game, all four freeze in one frame.

The classic bug

Removing items from that same array inside Loop Body. Every removal shifts the later items down, so the loop skips some.

Loop backwards with Reverse for Each Loop, or collect the items and remove them after Completed.

In short

One array in, every item handled, then Completed.

Covered in this lesson

  • For Each Loop
  • Array
  • Loop Body
  • Array Element
  • Array Index
  • Completed
  • Reverse for Each Loop

Newsletter

Development updates are coming to your inbox.

The newsletter opens soon. Until then, new lessons, tools and Beach Hunters progress appear first on our channels, linked below.