我想知道是否可以比较两个独立枚举(来自不同脚本)的 (int)?
我目前正在尝试:
if((int)newMiner.minerType == (int)resourceType)
{
Debug.Log("Resource Holder Accepts Miner");
}
newMiner 是另一个具有我要比较的枚举的脚本,minerType 是一个枚举,而 resourceType 是我试图与之比较的本地枚举。
我现在没有返回错误,但是,它总是返回 true。非常感谢任何关于它如何工作/不工作的信息:)
最佳答案
假设您有两个枚举
enum Car { Window, Door, Light, Gate, Bath }
enum House { Window, Door, Light, Bath, Gate }
然后你有他们的实例
Car car = Car.Window;
House house = House.Window;
你能直接和if (car == house)
比较吗? ?
没有
你能将它们的值与 if ((int)car == (int)house)
进行比较吗? ?
是。看起来这就是您要尝试做的。
示例 1:
if ((int)car == (int)house)
Debug.Log("Car Value matches House value");
else
Debug.Log("Car Value DOES NOT match House value");
输出:
Car Value matches House value
那是因为 Window
来自 Car
枚举和 Window
来自 House
Enum 都共享相同的 Enum 值索引,即 0
.
示例 2:
Car car = Car.Light;
House house = House.Light;
if ((int)car == (int)house)
Debug.Log("Car Value matches House value");
else
Debug.Log("Car Value DOES NOT match House value");
输出:
Car Value matches House value
同样,那是因为 Light
来自 Car
枚举和 Light
来自 House
Enum 都共享相同的 Enum 值索引,即 2
.
示例 3:
Car car = Car.Gate;
House house = House.Gate;
if ((int)car == (int)house)
Debug.Log("Car Value matches House value");
else
Debug.Log("Car Value DOES NOT match House value");
输出:
Car Value DOES NOT match House value
惊喜!惊喜!门与门自Car
和 House
枚举不匹配。 为什么?
因为 Gate
来自 House
枚举的值为 4
同时Gate
来自 Car
枚举的值为 3
. 4 != 3。
当您将 Enum 转换为 int 时,您将获得它的索引位置。位置从0
开始像一个数组。例如,下面的 Enum 声明代码向您展示了索引的样子。
enum Car { Window = 0, Door = 1, Light = 2, Gate = 3, Bath = 4 }
如果 if 语句是 true
, 他们都必须在同一个位置。你会得到 false
如果他们处于不同的位置。再次检查您的枚举并修复它。
关于c# - 比较 C#/Unity 中的枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753780/