Another KeyCode problem...

How can i convert like a normal string “KeyCode.A” to a KeyCode?

static var left : KeyCode = KeyCode.A;

i am sending the string “KeyCode.A” to the variable left in …left = “KeyCode.” + optionsleftkey;

optionsleftkey = A

Is there a special reason why you're not using [Input][1] for this? [1]: http://unity3d.com/support/documentation/ScriptReference/Input.html

yes i use Input in if(Input.KeyCode(left)) get it? thats so the key for left is changeable ingame

Ah I see! Let me think a bit

2 Answers

2

Here's an updated version, note that this is strictly made out of testing, so you'd have to make a function for setting the key and getting the key separate.

#pragma strict

static var leftKey : String;

function OnGUI () {
    var e : Event = Event.current;
    if (e.isKey && Input.anyKeyDown && e.keyCode.ToString()!="None") {
       SetKey (e.keyCode.ToString());
    }

    if(e.keyCode.ToString() == leftKey) {
        transform.position.x+=10*Time.deltaTime;
    }
}

function SetKey (incomingKey : String) {
    leftKey = incomingKey;
    Debug.Log(leftKey.ToString());
}

Basically just compare the strings. I might be able to give you a better example later where you compare directly against the actual KeyCode without conversion.

To later work with KeyCodes you can parse the KeyCode (which is an enum):

System.Enum.Parse(typeof(KeyCode), theString)

Thanks! i will try it out then i will set this question as awnsered! :D

Sorry I'm in a bit of a hurry (hence the mistake), hold on let me see if I can get it straight

Updated it with a quick testing script, do note that setting and getting is done in the same block and done from the GUI which is not preferable. I'll get back to you if you don't come up with a solution for your implementation.

this code: e.keyCode.ToString()!="None" is a rather ugly way of determing if there is a keycode. Why not use KeyCode.None ? http://unity3d.com/support/documentation/ScriptReference/KeyCode.None.html

Also mixing Input functions into OnGUI isn't really a good idea. Use events instead.

why don’t you just declare your leftKey as a KeyCode instead of a String? Just tested it, works perfectly (in 4,0, IDK about previous versions)