All courses / Data Structures and Algorithms for Game Devs / Bits and bytes
Bit flags
Challenge lesson, about 13 min, +20 XP
A goblin arrow can poison Nico, a fire bomb can set the hero burning, and the sea at night can freeze anyone who falls in. Nico can have all of those at once. You could give the hero one bool for each effect. A bool takes a whole byte, as you saw in C# Basics, so ten effects would cost at least ten bytes and ten variables to copy and save. There is a smaller way: keep every effect in one int, one bit each.
Give each effect its own bit position. Its value is then a power of two, with a single 1 in its bits:
Read the rest of this lesson and run the code in your browser.
Previous: Predict the output: binary and hex Next: Shifting bits