I have the following enum:
public enum Materials { Wood, Stone, Earth, Water, Lava, Air }
Now I have 3materials on which i could walk (wood stone earth) and 3 which arent walkable (water lava air)
I would like to make it possible to compare if a flag is one of the three.
At the moment, this is how I do it:
Materials myMat = Materials.Earth;
if ( myMat == Materials.Earth || myMat == Materials.Wood || myMat == Materials.Stone)
{
I can walk on myMat...
}
isnt it possible to create a new flag like Materials.Walkable which would include these three materials so I can just use
if ( myMat == Materials.Walkable )
If this is possible, how can I do that?
Thanks in advance ;)
You could create an extension method:
public static bool IsWalkable(this Materials myMat )
{
return myMat == Materials.Earth || myMat == Materials.Wood || myMat == Materials.Stone;
// alternatively:
return new[] { Materials.Earth, Materials.Wood, Materials.Stone }.Contains(myMat);
}
And use it as:
Materials myMat = ...
bool isMyMatWalkable = myMat.IsWalkable();
If you like, you could also use a [Flags] enum:
[Flags]
public enum Materials
{
None = 0,
Wood = 1,
Stone = 1 << 1,
Earth = 1 << 2,
Water = 1 << 3,
Lava = 1 << 4,
Air = 1 << 5,
Walkable = Wood | Earth | Stone
}
And then you can do:
Materials myMat = ..
bool isMyMatWalkable = (myMat & Materials.Walkable) != Materials.None;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With