Simon Verbeke
Simon Verbeke

Reputation: 3005

Can I 'invert' a bool?

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)

Upvotes: 77

Views: 158054

Answers (5)

Scover
Scover

Reputation: 138

This can be useful for long variable names. You don't have to write the variable name twice.

public static void Invert(this ref bool b) => b = !b;

Example:

bool superLongBoolVariableName = true;
superLongBoolVariableName.Invert()

Upvotes: 1

Jack
Jack

Reputation: 4904

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();

Upvotes: 12

Jack
Jack

Reputation: 4904

I think it is better to write:

ruleScreenActive ^= true;

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

Upvotes: 81

MusiGenesis
MusiGenesis

Reputation: 75276

ruleScreenActive = !ruleScreenActive;

Upvotes: 12

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

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

ruleScreenActive = !ruleScreenActive;

Upvotes: 182

Related Questions