【发布时间】:2019-06-16 17:49:28
【问题描述】:
在 C# 中(使用 Unity 处理游戏)我有一个带有 [Flag] 属性的枚举。我已经实例化了两次。我想要一种比较两个枚举的方法。特别是如果枚举 A(将有多个标志)包含来自枚举 B 的标志(只会分配一个标志)。
我不是试图将单个实例化枚举与单个标志进行比较(这已被多次回答)。
我怀疑我可以通过使用 GetValue 转储值并在 foreach 循环中比较这些值来做到这一点,但似乎应该有更直接的比较方法。
public enum AbilityType
{
None = 0,
Pierce = 1<<1,
Blunt = 1<<2,
Slash = 1<<3,
Water = 1<<4,
// etc.
};
public class Ability : MonoBehaviour
{
public AbilityType abilityType;
}
public class AbilitiedObject : StatisticalObject
{
public AbilityType resistances;
protected override void Awake()
{
base.Awake();
resistances = AbilityType.Pierce | AbilityType.Water;
}
public void TakeDamage(int damageAmount, AbilityType abilityType)
{
if( ) // Check if resistances contains abilityType's flag here
{
print("You are resistance to this damage type");
}
else
{
// Player takes damage
}
}
}
我希望上面的代码检查阻力是否包含来自能力类型的标志。在上面的示例中,所讨论的攻击将传递它的能力类型。如果该类型是水或穿刺,它应该打印抵抗声明。如果是其他类型,它应该正常造成伤害。
【问题讨论】:
-
SO Article 对您有用吗?听起来你想要按位运算。像这样
if(resistances & abilityType == abilityType)...不是在电脑上。 -
不要试图听起来专横,但标志在互联网上被广泛记录。你可以谷歌“flag c#”,你很可能会找到一个快速的答案。
-
Most common C# bitwise operations on enums 的可能重复项。从字面上看,最佳答案有你想要的。
-
@DrakeBarron “两个枚举”和“一个枚举和一个标志”之间没有任何区别。
-
顺便说一下
(a & b) != 0和(a & b) == b的区别在于,第一个检查b的标志中的any 是否设置在@ 987654329@,第二个检查是否设置了所有个。
标签: c# unity3d enums enum-flags