- Home /
Make an int switch?
Im making a menu system and every time the player presses escape, i want the an int called currentPanel to go down, so it knows when the menu is closed. however, when the menu is at -1, i want it to open the first panel rather than closing it.
so heres what would happen if you had the 4th menu panel open and pressed esc 5 times:
move to 3.
move to 2.
move to 1.
move to 0.
close menu.
open menu 0.
i tried
if (Input.GetKeyDown (KeyCode.Escape))
{
if (CurrentPanel < 0)
{
CurrentPanel ++;
}
if (CurrentPanel == 0)
{
CurrentPanel --;
}
but it doesnt work because when one switches, the other switches.
A switch statement is good for this. However, don't assume that Javascript learned for w3schools is going to work in Unity; it doesn't support web Javascript. Ins$$anonymous$$d its a mashup of javascript actionscript and some other nonsense (which all together works quite well).
Sorry to bother again, but what is the difference between @alfalfasprout answer and my code?
Answer by Alanisaac · Feb 11, 2015 at 01:38 PM
Just need an else before the if as below. Otherwise, both statements will execute, and you're back at -1.
if (Input.GetKeyDown (KeyCode.Escape))
{
if (CurrentPanel < 0)
{
CurrentPanel ++;
}
else if (CurrentPanel == 0)
{
CurrentPanel --;
}
}
Answer by VesuvianPrime · Feb 11, 2015 at 01:38 PM
A switch like you're asking for would be:
switch (CurrentPanel)
{
case -1:
CurrentPanel++;
break;
case 0:
CurrentPanel--;
break;
// and so on
}
For a more robust menu system I would implement something like the following:
public enum Menu
{
Main,
Options,
NewGame,
Etc
}
private Stack<Menu> m_MenuStack;
public void GoToMenu(Menu menu)
{
m_MenuStack.Push(menu);
}
public void GoToPreviousMenu()
{
m_MenuStack.Pop();
if (m_MenuStack.Count == 0)
GoToMenu(Menu.Main);
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
GoToPreviousMenu();
}
public void OnGUI()
{
Menu current = m_MenuStack.Peek();
switch (current)
{
case Menu.Main:
// Draw the main menu
break;
case Menu.Options:
// Draw the options menu
break;
// etc
default:
throw new System.ArgumentOutOfBoundsException();
}
}
unity just gives an error, apparently using ints is invalid in switch statements
Your answer
