How apply something like the "!" Operator to an enum?
So hey Guys, latley I am working with enums, and now I came to the point were I want an if-statement to return true when the game is not in the current gamestate (enum). The Code looks simplified like this:
public enum GameState { Phase1, Phase2, Phase3);
public Class Classname : MonoBehaviour
public GameState currentState;
{
public void Start
{
currentState=GameState.Phase1;
}
public void Update
{
if (//SomeCode// && currentState==!GameState.Phase2)
{
//Some Code//
}
}
But Unity says that enums cant work with the !-Operator (CS0023). Is there another way to make the if-Statement return true if some State but not "Phase2" is the current state ? thx and pls excuse my english skills ;)
Answer by Bunny83 · Mar 17, 2020 at 02:24 PM
You got some major confusion here. An enum is equivalent to an ordinate integer value- Each enum member has a numerical value assigned. So all you do is comparing numbers. Applying the boolean operator "NOT" i.e. the unary !
operator to a number doesn't make much sense. What do you thing !5
should return?
What you are looking for is the not-equal operator !=
which returns true when the two compared values are not equal. The != operator is just a shorthand. The expression A != B
is the same as !(A == B)
So if you want to test that your state is not "Phase2" (so any other state) you should do
if (currentState != GameState.Phase2)
Answer by unity_5yzdxMwy3aHi5Q · Mar 17, 2020 at 02:52 PM
Oh yeah that makes sense, I messed that one up. much thanks for the fast and informative respond.