Trying to toggle layers for background and foreground

I am trying to make a game where the player goes back and forth between the foreground and the background. I have gotten it to work using two keypresses but cannot figure out how to make it a toggle.

This is the Foreground script

public class Foreground : MonoBehaviour
{
    private void Start()
    {
        gameObject.layer = 9;
    }

    void Update()
    {
        var onoff = true;

        if (Input.GetKeyDown(KeyCode.G))
        {
            onoff = !onoff; // toggles onoff at each click

            if (onoff)
            {
                gameObject.layer = 9;
            }
            else
            {
                gameObject.layer = 10;
            }
        }
    }
}

And this is the background script

public class Background : MonoBehaviour
{
    private void Start()
    {
        gameObject.layer = 10;
    }

    void Update()
    {
        var onoff = true;

        if (Input.GetKeyDown(KeyCode.G))
        {
            onoff = !onoff; // toggles onoff at each click

            if (onoff)
            {
                gameObject.layer = 10;
            }
            else
            {
                gameObject.layer = 9;
            }
        }
    }
}

While trying to use the toggle it switches the layers correctly once but then does not seem to toggle back. In other words the layers won’t reverse again. What am I doing wrong here? Thanks!

You’re declaring and setting your onoff boolean to true every single Update. You don’t even need the bolean, just check if the layer is 9 then set it to 10 else set it to 9 and vice versa in the other script.

Aha! Duh. That makes it a lot simpler, thank you very much. That seems to work!

1 Like