Skip to content

Instantly share code, notes, and snippets.

@michaelbartnett
Created January 14, 2016 21:35
Show Gist options
  • Select an option

  • Save michaelbartnett/d32838d107200b1c6919 to your computer and use it in GitHub Desktop.

Select an option

Save michaelbartnett/d32838d107200b1c6919 to your computer and use it in GitHub Desktop.
Just the cake, can't eat it
// I have some enum ranges that I'm trying to keep in sync:
// I have some powerups:
enum PowerUpID
{
Missile,
Bomb,
}
// And some thingies:
enum ThingyID
{
Box,
Rock,
Tree,
}
// PowerUps and Thingies are valid target types, and there are other
// target types not defined in either of those enums:
enum Targets
{
Missile,
Bomb,
Box,
Other,
Things,
Player, // not in PowerUpID or ThingyID
}
// So if I modify one of the sub-enums, it borks:
enum PowerUpID
{
Missile,
Bomb,
LazerPewPew, // PowerUpID.LazerPewPew now maps to Targets.Box
}
// So I would like to define Targets like this:
enum Targets
{
Missile = (int)PowerUpID.Missile,
Bomb,
Box = ENUM_VALUE_COUNT(PowerUpID) + 1,
Other,
Things,
Player = ENUM_VALUE_COUNT(ThingyID), // not in PowerUpID or ThingyID
}
// That way I can add things to either PowerUpID or Targets and it won't break if I
// forget to update Targets.
// And, since each enum group follows the other, I can iterate over values of Targets
// really easily and treat them as array indices without holes.
// There would be runtime errors when I forget to sync the enum defs, but they'd be easy to
// assert on and lead me back to the source of the problem.
// But the way to get the number of enum members is a runtime thing:
enum Targets
{
Missile = (int)PowerUpID.Missile,
Bomb,
Box = Enum.GetValues(typeof(PowerUpID)).Length + 1,
Other,
Things,
Player = Enum.GetValues(typeof(ThingyID)).Length + 1, // not in PowerUpID or ThingyID
}
// But this kills the compiler.
// So instead I'm doing the basic thing:
enum Targets
{
Missile = (int)PowerUpID.Missile,
Bomb,
Box = 0x100, // there probably won't be 255 powerup types
Other,
Things,
Player = 0x200, // not in PowerUpID or ThingyID. hopefully there aren't 255 thingies.
}
// Now the enum values are not contiguous, so it's not as simple to
// iterate over all target types. Womp womp. I guess it's a little nitpicky, but Jai could do it!
// Or I could do it in Unity if there was a post-compile code injection workflow we had access to.
// To make sure I don't overlap and am not missing cases, I put some assertions in a static constructor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment