简体   繁体   中英

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. 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 .

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. In your case that means 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM