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!