Can I 'invert' a bool?
C#BooleanC# Problem Overview
I have some checks to see if a screen is active. The code looks like this:
if (GUI.Button(new Rect(Screen.width / 2 - 10, 50, 50, 30), "Rules")) //Creates a button
{
if (ruleScreenActive == true) //check if the screen is already active
ruleScreenActive = false; //handle according to that
else
ruleScreenActive = true;
}
Is there any way to - whenever I click the button - invert the value of ruleScreenActive
?
(This is C# in Unity3D)
C# Solutions
Solution 1 - C#
You can get rid of your if/else statements by negating the bool's value:
ruleScreenActive = !ruleScreenActive;
Solution 2 - C#
I think it is better to write:
ruleScreenActive ^= true;
that way you avoid writing the variable name twice ... which can lead to errors
Solution 3 - C#
ruleScreenActive = !ruleScreenActive;
Solution 4 - C#
This would be inlined, so readability increases, runtime costs stays the same:
public static bool Invert(this bool val) { return !val; }
To give:
ruleScreenActive.Invert();