Last active
October 18, 2016 16:04
-
-
Save AlbinoGeek/bfda2773edad0eda8ccf282c3cf80982 to your computer and use it in GitHub Desktop.
People keep asking me how to use an `enum` or `FlagsAttribute` or bitwise, so here goes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Flags] | |
public enum attackType | |
{ | |
// Enums should have a 0 value | |
None = 0, | |
Melee = 1 << 0, | |
Ranged = 1 << 1, | |
Thrown = 1 << 2 | |
} | |
public enum damageType | |
{ | |
// Enums should have a 0 value | |
None = 0, | |
Slash = 1 << 0, | |
Pierce = 1 << 1, | |
Bludgeon = 1 << 2, | |
Cold = 1 << 4, | |
Erode = 1 << 5, | |
Heat = 1 << 6, | |
Charge = 1 << 7, | |
Force = 1 << 8, | |
} | |
public class Weapon { | |
public AttackType Attack; | |
public DamageType Damage; | |
} | |
public void main() | |
{ | |
// Example usages | |
var Blade = new Weapon { | |
Attack = attackType.Melee, | |
Damage = damageType.Slash | |
}; | |
var Knife = new Weapon { | |
Attack = attackType.Melee, | |
// It does both (BITWISE OR) | |
Damage = damageType.Slash | damageType.Pierce, | |
}; | |
// normally you'd instantiate something, but here's just an example | |
var weapon = Knife; | |
// Can this wepaon slash? (BITWISE AND) | |
if ((weapon.Damage & DamageType.Slash) != 0) {} | |
// True for both | |
// Can this weapon bludgeon? (BITWISE AND) | |
if ((weapon.Damage && DamageType.Bludgeon) != 0) {} | |
// False for both | |
// ADD Bludgeon to the weapon (BITWISE NOT) | |
weaopn.Damage &= DamageType.Bludgeon | |
// REMOVE Cold to the weapon (BITWISE NOT) | |
weaopn.Damage &= - DamageType.Cold | |
// TOGGLE Heat to the weapon (BITWISE XOR) | |
weapon.Damage ^= DamageType.Heat | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment