In preparation for some serious game coding in the new year with code jams, OGAM, and hopefully more, I’m creating a template for all my Unity games. I really don’t want to deal with creating a title screen, menus, and all that jazz, so I’m preparing this now. It’s actually somewhat easy once you start reading everyone’s solutions to problems, so I’ll consolidate some of those resources here. By the way, if you want to check out the template, it’s located at https://github.com/monkeysSuck/BaseUnityProject.
Controller Input and Menus
The element you’ll probably be rushing to use to create a GUI is the standard button (GUI.Button). However, there’s a much better object to use: GUI.SelectionGrid. With this, you can consolidate input methods as well:
public const float fMaxJoystickRange = 0.8f; // Joystick range for detecting input void Update() { if (Input.GetButtonUp("Up") || Input.GetAxis("Vertical") < -fMaxJoystickRange) { iSelected = Mathf.Max(iSelected - 1, 0); } else if (Input.GetButtonUp("Down") || Input.GetAxis("Vertical") > fMaxJoystickRange) { iSelected = Mathf.Min(iSelected + 1, arrButtonNames.Length - 1); } else if (Input.GetButtonUp("Select") || (GUI.changed && Input.GetMouseButtonUp(0)) || Input.GetButtonUp("Select (Controller)")) { ProcessInput(); } }
The best part about this? It handles mouse, keyboard, and controller. All of these inputs are set via InputManager. For the mouse input, I do an additional check for GUI.changed because we want to avoid clicks outside of the GUI.
Pausing the game
Pausing the game is also quite easy. Adding a small script that gets added/removed when a button is pushed. In this script, when the script is initialized, store the old Time.timeSpan value and set Time.timeSpan to 0. Then, in the script’s OnDestroy method, reset Time.timeSpan to the stored value.