Learn

Chapter 05 Functions & Collections

#048 Sets

Your explorer achievement unlocks too early? Your array is counting duplicates.

  • 1:16 video
  • Written lesson
  • Beginner
Video lesson: Sets, 1:16

Unique values only

Arrays accept the same value twice, so every revisit adds another entry.

A Set stores unique values, with no keys and no index. Create a variable, and change its container type to Set.

  • Adding a value that’s already there does nothing. Duplicates are simply ignored.
  • Contains checks membership without a loop, and Remove deletes a value.
  • Add Items adds a whole array, and drops its duplicates too.

Like maps, sets keep no reliable order, and set variables can’t replicate.

Example: an explorer achievement

A Visited Zones set drives the achievement.

  • Enter the forest: Add Forest, Length is one.
  • Enter the cave: Length is two.
  • Back to the forest? Add does nothing, so Length stays at two.
  • Reach the lake, Length hits three, and the achievement unlocks.

With an array, that revisit would count, and the achievement would unlock early.

Tips

  • Sets have no index, so there’s no Get. To loop over one, call To Array first.
  • To compare two sets, use Union, Intersection or Difference. Required Keys, Difference with Owned Keys, gives you the keys still missing.
  • Sets also hold actor references, like enemies already hit by a single sword swing.

In short

Need each value once? Use a Set.

Covered in this lesson

  • Set
  • Add
  • Contains
  • Remove
  • Add Items
  • Length
  • To Array
  • Union
  • Intersection
  • Difference

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.