- Home /
Quick question about Input.GetKey and Input.GetKeyUp
Hi, I'm using futile to create a 2d game prototype. I have a textbox where user input is stored, but the backspace key doesn't work automatically so I had created the following:
public void HandleInput()
{
DisplayInput.text = DisplayInput.text + Input.inputString;
if(Input.GetKey(KeyCode.Backspace))
{
if(DisplayInput.text.Length != 0)
DisplayInput.text = DisplayInput.text.Remove(DisplayInput.text.Length -1);
}
}
This problem is that this script removes mutiple characters (since backspace is held for multiple frames.
So I changed the code to the following:
public void HandleInput()
{
DisplayInput.text = DisplayInput.text + Input.inputString;
if(Input.GetKeyUp(KeyCode.Backspace)) //this is the only line that changed
{
if(DisplayInput.text.Length != 0)
DisplayInput.text = DisplayInput.text.Remove(DisplayInput.text.Length -1);
}
}
This does not remove any characters, when I add a Debug.Log I can see that the function does fire when the backspace key is released, it just doesn't remove the characters.
Any help would be great.
If by textbox you mean GUI.TextField or TextArea, the backspace key does work automatically.
I know, I'm trying to implement the backspace key but my code doesn't seem to work.
The point is that you don't need to do this; Unity already does it for you.
Input.inputString captures the backspace key in the string, so your code is just removing the backspace from the string. Note that inputString can contain more than one character, so the method you are using here will have problems if the frame that has the backspace captures more than one key.
Answer by DuckerDuck · Jul 01, 2013 at 08:00 PM
@Eric5h5 oh, sorry misread your post, I'm not using GUI but a text field of Futile.
@robertbu I think I understand, so Its like enter is \\n and etc
Thanks for the answer I think i'll manage to fix it.
EDIT: I took a look at the example here, and this is my new code:
public void HandleInput()
{
foreach (char c in Input.inputString) {
if (c == "\b"[0]){
if (DisplayInput.text.Length != 0)
DisplayInput.text = DisplayInput.text.Remove(DisplayInput.text.Length -1);
}
else
if (c == "\n"[0] || c == "\r"[0])
Debug.Log("Character not allowed");//might use this in the future
else
DisplayInput.text += c;
}
}
Sorry for being such a noob.