Assign keystrokes to GUI button

Is there a way to assign a keystroke to a GUI button?

I'm attempting to control my game character through MouseEvents on GUI buttons and have been running into problems, which could all be solved if I could link up keyboard hits (wasd and arrows) to the GUI.

You shouldn't use the Input class inside OnGUI because that can break the GUI system and can bring up errors. Inside OnGUI you should use the Event class.

Here's a little helper function (C#):

bool GUIKeyDown(KeyCode key)
{
    if (Event.current.type == EventType.KeyDown)
        return (Event.current.keyCode == key);
    return false;
}

And the same in JS (Unityscript)

function GUIKeyDown(key : KeyCode) : bool
{
    if (Event.current.type == EventType.KeyDown)
        return (Event.current.keyCode == key);
    return false;
}

Here an example how to use this function inside OnGUI():

{
   if (GUIKeyDown(KeyCode.W)) // the "W" key
   {
      [...]
   }

But be warned: it does not work like Input.GetKeyDown() function because Event actually maps the windows messages like WM_KEYDOWN. The function will also return true when a key is autorepeated by the OS. To simulate Input.GetKey() you would need to keep track of both events EventType.KeyDown and EventType.KeyUp but that would get to complicated.

If you need this functionality i recomend to but your actual code, that should be executed by GUI.Button or by a key, in a seperate function. Call that function from your OnGUI() with your GUI.Button and do the Key-check in Update().

You may also have a look at Event.KeyboardEvent

You can assign keys to things using the Input Manager. You can program them directly by looking for key press/hold/release in any Update or OnGUI function. As far as declaring or defining an 'accelerator' for a GUI button, I don't think so, but that would be nice. I suppose one could write a subclass to do that, and maybe even sell it cheap on the Asset Store.