Find Out What Key A Button Is

Hello,

I have a tutorial section on my game, and I want to give onscreen instructions on what the player needs to press on the keyboard.

For example, the ACTION button is ‘E’ by default. So I want to say something like “Press ‘E’ to activate”. Which is fine, but what if the player wants to change the buttons around on the settings.

I want to be able to ask Unity what Key the ‘ACTION’ Button is set at, so I can dynamically change my onscreen instructions.

Thanks

----- UPDATE ----

I don’t think I have explained myself very well. When the user starts up Unity, they have the option to change the Input Keys. For example, there is one I have made called ‘Action’, which is associated with key ‘E’. But the user might change that. So I want to check with Unity, what key has been assigned to ‘Action’.

Unity does not expose the built in Input Manager to scripting. Sadly, there is no way to find what keys are assigned to the axes at runtime. In your situation the best bet would be to create your own system for the management and customization of action keys. It is a bit of work, but in the end it is well worth it if you want to allow the user to customize the control scheme.

You can disable the configuration dialog when the the game starts to prevent the user from having access to changing such configurations. See this answer if you would like to do that: How to Remove Configuration Box

Hope that answers your question.

Another way is by doing this:

var actionKey : KeyCode = KeyCode.E;

function Update () {
    if(Input.GetKeyDown(actionKey)) {
        Debug.Log("Pressed the action key: " + actionKey);
    }
}

function OnGUI () {
    GUI.Label(Rect(10,10,200,20),"Press " + actionKey + " to activate.");
}

By doing this, you can change the action button at any time. For example:

if(GUI.Button(Rect(10,10,200,20),"Change actionKey to T")) {
    actionKey = KeyCode.T;
}

I assume you mean the keys you can assign in Edit → Project Settings → Input. I had the same problem some time ago. I ended up disabling the configuration screen and doing my own Input manager class, which I could then query for what key was set to which function. I also had to do all resolution and key changes from within the game.

public var actionKey = “e”;

function Update () {
    if (Input.GetKeyUp (actionKey))
    {
        print ("action!");
        // do cool action stuff
    }
}

And then just have the player be able to change the actionKey variable through a GUI or whatever. Maybe something like:

function OnGUI () {
    actionKey = GUI.TextField (Rect (10, 10, 100, 20), actionKey, 1);
}