- Home /
The question is answered, right answer was accepted
How to navigate through UI buttons without keyboard arrows?
Hi all,
I have some buttons in a UI canvas. The navigation through the UI works fine with the keyboard Arrows.
Now i am trying to handle the navigation with another Input device, that cannot be recognized by Unity automatically. So i just have a boolean that becomes true if i click "Up" or "Right" with this device.
Is it possible to call the same navigation / move -function like the Left/Right/Up/Down Arrows on the keyboard but just for a boolean input?
So what i want is:
if (Device.boolUp == true)
{
//navigate left in UI
}
and so on for Left / Right / Down. Thanks for your Help!
Answer by LenaWi · Jan 20, 2021 at 04:31 PM
@IBXCODECAT Thanks for your answer!
By chance i found this code:
EventSystem.current.SetSelectedGameObject(button.FindSelectableOnDown().gameObject);
I think this FindSelectableOnDown() is what i was searching for. So probably when i first ask for the actually selected button and then tell the system to select the down button it could hopefully work.
Answer by IBXCODECAT · Jan 20, 2021 at 04:19 PM
Unity uses the event system (that is automatically created when creating UI or a canvas.) In the event system there should be references to input axis. Try changing the axis. Unfortunately you can not do this through code, if you want this to work at run-time try making your own input manager.
public static class GameInputManager
{
static Dictionary<string, KeyCode> keyMapping;
static string[] keyMaps = new string[6]
{
"Attack",
"Block",
"Forward",
"Backward",
"Left",
"Right"
};
static KeyCode[] defaults = new KeyCode[6]
{
KeyCode.Q,
KeyCode.E,
KeyCode.W,
KeyCode.S,
KeyCode.A,
KeyCode.D
};
static GameInputManager()
{
InitializeDictionary();
}
private static void InitializeDictionary()
{
keyMapping = new Dictionary<string, KeyCode>();
for(int i=0;i<keyMaps.Length;++i)
{
keyMapping.Add(keyMaps[i], defaults[i]);
}
}
public static void SetKeyMap(string keyMap,KeyCode key)
{
if (!keyMapping.ContainsKey(keyMap))
throw new ArgumentException("Invalid KeyMap in SetKeyMap: " + keyMap);
keyMapping[keyMap] = key;
}
public static bool GetKeyDown(string keyMap)
{
return Input.GetKeyDown(keyMapping[keyMap]);
}
}
You could use it like this:
void Update()
{
if (GameInputManager.GetKeyDown("attack"))
{
//Do stuff
}
}
instead of this:
if(Input.GetKeyDown(Keycode.W)
{
//Do Stuff
}
Do stuff would be what you wanted to happen when you gave the input
Answer by IBXCODECAT · Jan 20, 2021 at 04:22 PM
Also you could create multiple 'inputs' in the default input manager and switch between them.
switch(inputMethod)
{
case 1:
//Use axis 1
break;
case 2:
//Use axis 2
break;
case 3:
//Use axis 3
break;
default:
//Axis invalid
}