- Home /
Strange string appending
Hi, i am trying to make a basic chat window, but when i try to build the string from the character pressed by the user on the keyboard, it get very strange. If i write the following message "Hello", the actual string seems to look something like this: "H e l l o" and not "Hello" as i want it to be.
I can see the error when i try to delete a character in the inputTextBox window. I need to press backspace twice for one character to be removed.
public class ChattWindow : MonoBehaviour {
private string inputField = " ";
private Vector2 scrollPosition = Vector2.zero;
//StringBuilder sb;
private string ChattWindowText = "";
// Use this for initialization
void Start () {
//sb = new StringBuilder();
}
// Update is called once per frame
void Update () {
}
void Awake(){
}
void OnGUI(){
Event e = Event.current;
int i = 0;
if(e.type == EventType.keyDown && e.keyCode == KeyCode.Return){
ChattWindowText = ChattWindowText + inputField;
while(i != inputField.Length){
Debug.Log(inputField[i]);
i++;
}
inputField = "";
}else if(e.type == EventType.keyDown && e.keyCode == KeyCode.Backspace){
inputField = inputField.Substring(0,inputField.Length - 1);
Debug.Log(inputField.Length);
Debug.Log(inputField);
}else if(e.type == EventType.keyDown){
inputField = inputField + e.character;
}
GUILayout.BeginArea(new Rect (0,Screen.height - 250,300,200));
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(300), GUILayout.Height(200));
GUILayout.Label(ChattWindowText);
GUILayout.EndScrollView();
GUILayout.EndArea();
GUI.TextField (new Rect (0,Screen.height - 50,300,50), inputField);
}
}
OnGUI can be called multiple times. How many times does your else if(e.type == EventType.keyDown){
code get executed per frame?
Oh, it seems it get called two times, why does OnGUI get two calls?
Because that's the documented behaviour, and because you might get multiple events.
$$anonymous$$ove your text update logic(key presses and such) to the update function/method, your inputfield is accessible from out side the functions/methods.