I'm a very new Unity developer who's looking for a best practice or framework for handling different input modes. I'm working in C#. Here's a contrived example:

Sample Map Application

Control Scheme 1:

  • W/A/S/D keys move map up/right/down/left.
  • Escape key closes application

Spacebar opens menu and switches to Control Scheme 2

Control Scheme 2:

  • W/A/S/D moves menu selection up/down/into submenu/back to parent menu.
  • Escape key closes menu and switches to Control Scheme 1

I realize this is a silly contrived example, but it demonstrates the point. When we are in a menu we don't want the W/A/S/D keys to also move the map while we are trying to navigate the menu. This could be done with a bunch of if statements such as

   // read keypresses and move map
else if(menuMode)
   // read keypresses and menu navigation

But you can see how this would get messy very quickly if we had lots of modes. We could also end up with a lot of nested if statements if we have sub-modes for controls.

Surely there's a cleaner way to do this? Any best practices for this? Any frameworks?


Event handlers.

When your map is open or gains focus, it subscribes to key events.

InputManager.OnKeyPressed += HandleKeyPress;

When your map closes or loses focus, it unsubscribes from key events.

InputManager.OnKeyPressed -= HandleKeyPress;

Here's a Unity example and video about it.

  • \$\begingroup\$ My use case actually uses joystick values as well. So I don't know if an event-driven system is sufficient. \$\endgroup\$ – J-bob Apr 30 '18 at 20:24
  • 1
    \$\begingroup\$ It is. It's the same strategy. Joystick changes can be event driven as well. \$\endgroup\$ – MichaelHouse Apr 30 '18 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.