Can I 'invert' a bool?

前端 未结 4 539
盖世英雄少女心
盖世英雄少女心 2020-12-03 06:36

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          


        
相关标签:
4条回答
  • 2020-12-03 06:52

    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();
    
    0 讨论(0)
  • 2020-12-03 07:02

    I think it is better to write:

    ruleScreenActive ^= true;
    

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

    0 讨论(0)
  • 2020-12-03 07:06

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

    ruleScreenActive = !ruleScreenActive;
    
    0 讨论(0)
  • 2020-12-03 07:06
    ruleScreenActive = !ruleScreenActive;
    
    0 讨论(0)
提交回复
热议问题