DEV Community

Mohak Jain
Mohak Jain

Posted on

Toggling state of a bool value

I have seen many beginners do this mistake and when I started out I did this mistake too so lets see what the mistake is and how to fix it.
So lets say you have a bool Variable called LightState which manages if the light switch is on or off. Now say when player presses a key for example "F" then you want to change it most people write the following.

    bool LightState = false;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            // If the Lightstate is false then make it true
            if (LightState == false)
            {
                LightState = true;
            }
            else //If Lightstate is true make it false
            {
                LightState = false;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Now this code is simple but it will take a little more time to read so instead you can do the following

    bool LightState = false;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Whatever the lighstate is make it opposite of that.
            LightState = !LightState;
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)