[英]How to check if my Bool value is true in unity c#?
im using unity 2018 and using c# i want to check if my bool value is true.我使用统一 2018 并使用 c# 我想检查我的布尔值是否为真。 this is my code:这是我的代码:
public class ShopButtonClick : MonoBehaviour
{
bool shopOpened = false;
public GameObject upgradeOne;
public void ClickTheButton()
{
if (shopOpened)
{
shopOpened = false;
upgradeOne.SetActive(false);
}
else
shopOpened = true;
upgradeOne.SetActive(true);
}
}
the problem is that it doesnt work, i added the script to the button and it wont work, on my other project it works ok... but for some reason not now.问题是它不起作用,我将脚本添加到按钮并且它不起作用,在我的其他项目上它工作正常......但由于某种原因现在不行。
You are missing brackets:您缺少括号:
if (shopOpened)
{
shopOpened = false;
upgradeOne.SetActive(false);
}
// without brackets the else only applies to the first line of code after it
else
shopOpened = true;
// This is always executed
upgradeOne.SetActive(true);
What you want is probably你想要的大概是
if (shopOpened)
{
shopOpened = false;
upgradeOne.SetActive(false);
}
else
{
shopOpened = true;
upgradeOne.SetActive(true);
}
In fact I would rather write it simply as事实上,我宁愿把它简单地写成
public void ClickTheButton()
{
// invert the bool flag
shopOpened = !shopOpened;
// directly re-use its value
upgradeOne.SetActive(shopOpened);
}
you are missing a curly bracket after else
.你在else
之后缺少一个大括号。
While you can write an if/else statement without brackets only the first line after else
will be treated as belongig to the else statement.虽然您可以编写不带括号的 if/else 语句,但只有else
之后的第一行将被视为属于 else 语句。 In your case that means upgradeOne.SetActive(true);
在您的情况下,这意味着upgradeOne.SetActive(true);
will always be exexuted because it will be interpreted as.将始终被执行,因为它将被解释为。
if (shopOpened)
{
shopOpened = false;
upgradeOne.SetActive(false);
}
else
{
shopOpened = true;
}
upgradeOne.SetActive(true);
I would always add brackets to exactly prevent this kind of bugs.我总是会添加括号来完全防止这种错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.