I was wondering if it is possible to compare the (int) of two seperate Enums (from different scripts)?
if((int)newMiner.minerType == (int)resourceType)
{
Debug.Log("Resource Holder Accepts Miner");
}
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.
You can't do this.
Just have one publicly-available enum! Use the same in both places.
But I need it in menu and component. How do I make a public and include?
"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.