我可以“反转”吗?一个布尔?

发布于 2024-12-28 04:20:18 字数 446 浏览 2 评论 0原文

我进行了一些检查来查看屏幕是否处于活动状态。代码如下所示:

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;
    }

有没有办法 - 每当我单击按钮时 - 反转 ruleScreenActive 的值?

(这是Unity3D中的C#)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

2025-01-04 04:20:18

您可以通过否定 bool 的值来摆脱 if/else 语句:

ruleScreenActive = !ruleScreenActive;

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

ruleScreenActive = !ruleScreenActive;
银河中√捞星星 2025-01-04 04:20:18

我认为最好这样写:

ruleScreenActive ^= true;

这样就可以避免将变量名写两次......这可能会导致错误

I think it is better to write:

ruleScreenActive ^= true;

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

以歌曲疗慰 2025-01-04 04:20:18
ruleScreenActive = !ruleScreenActive;
ruleScreenActive = !ruleScreenActive;
血之狂魔 2025-01-04 04:20:18

这将被内联,因此可读性增加,运行时成本保持不变:

public static bool Invert(this bool val) { return !val; }

给出:

ruleScreenActive.Invert();

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();
悲喜皆因你 2025-01-04 04:20:18

这对于长变量名很有用。您不必将变量名称写两次。

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

例子:

bool superLongBoolVariableName = true;
superLongBoolVariableName.Invert()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文