'Comparing enum values in C#/Unity?
I was wondering if it is possible to compare the (int) of two seperate Enums (from different scripts)?
I am currently trying:
if((int)newMiner.minerType == (int)resourceType)
{
Debug.Log("Resource Holder Accepts Miner");
}
newMiner is the other script that has the enum I'm trying to compare and minerType is one Enum while resourceType is the local Enum I am trying to compare it with.
What I have now does not return an error, however, it always returns true. Any information on how this does/doesn't work would be very much appreciated :)
Solution 1:[1]
Let's say you have two enums
enum Car { Window, Door, Light, Gate, Bath }
enum House { Window, Door, Light, Bath, Gate }
Then you have instance of them with
Car car = Car.Window;
House house = House.Window;
Can you compare them directly with if (car == house)?
NO
Can you compare their values with if ((int)car == (int)house)?
Yes. It looks like this is what you are trying to do.
Example 1:
if ((int)car == (int)house)
Debug.Log("Car Value matches House value");
else
Debug.Log("Car Value DOES NOT match House value");
Output:
Car Value matches House value
That's because Window from Car Enum and Window from House Enum both share the-same Enum value index which is 0.
Example 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");
Output:
Car Value matches House value
Again, that's because Light from Car Enum and Light from House Enum both share the-same Enum value index which is 2.
Example 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");
Output:
Car Value DOES NOT match House value
Surprise! Surprise! Gate and Gate from Car and House Enum don't match. Why?
Because Gate from House Enum has a value of 4 and while Gate from Car Enum has a value of 3. 4 != 3.
When you cast Enum to int, you will get its index position of it. The position starts from 0 like an array. For example, the Enum declaration code below shows you what the index looks like.
enum Car { Window = 0, Door = 1, Light = 2, Gate = 3, Bath = 4 }
For the if statement to be true, they both have to be at the-same position. You will get false if they are in different position. Check your Enum again and fix that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Programmer |
