Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I 'invert' a bool?

Tags:

c#

boolean

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)

like image 919
Simon Verbeke Avatar asked Jan 18 '12 15:01

Simon Verbeke


People also ask

What operator is used to negate or take the opposite of a boolean value?

The logical NOT ( ! ) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true ; otherwise, returns true .

Is bool true 1 or 0?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.


2 Answers

You can get rid of your if/else statements by negating the bool's value:

ruleScreenActive = !ruleScreenActive; 
like image 67
Ahmad Mageed Avatar answered Oct 05 '22 11:10

Ahmad Mageed


I think it is better to write:

ruleScreenActive ^= true; 

that way you avoid writing the variable name twice ... which can lead to errors

like image 33
Jack Avatar answered Oct 05 '22 10:10

Jack