- Home /
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 for this?
yes i use Input in if(Input.$$anonymous$$eyCode(left)) get it? thats so the key for left is changeable ingame
Answer by save · Oct 02, 2011 at 10:41 AM
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 deter$$anonymous$$g if there is a keycode. Why not use $$anonymous$$eyCode.None ? http://unity3d.com/support/documentation/ScriptReference/$$anonymous$$eyCode.None.html
Also mixing Input functions into OnGUI isn't really a good idea. Use events ins$$anonymous$$d.
Answer by SupaFinga · Apr 20, 2013 at 02:45 AM
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)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Converting string of a key into KeyCode 2 Answers
Another Error - Enum.Parse 1 Answer
convert string to int 0 Answers
Disable a Key after shooting 3 Answers