I am trying to create a dialogue system where the dialogue will continue if the player press E. However, if the player press E too quickly, the dialogue text will become gibberish as shown in the screenshot.
Please advise. Thanks
IEnumerator Type()
{
foreach (char letter in sentences[index].ToCharArray())
{
displayText.text += letter;
yield return new WaitForSeconds(typingspeed);
}
}
public void NextSentenceGuitar()
{
if (index < sentences.Length - 1)
{
I dont know what else happens when pressed on E (maybe problem lying under there) but i could suggest that to prevent user press E too early. Just define a bool e.g. typing to keep track of your typing activity. Set it false initially and when typing coroutine starts set it true (or when you need it).
if(Input.GetKeyDown(KeyCode.E) && typing){
//do your stuff
}
This is happening because the previous Type() coroutine keeps going even if you start a new one. So if the user presses E twice in rapid succession, the first Type() method will start adding letters from sentences[0] and the second will start adding letters from sentences[1] simultaneously, causing the sentences to interleave with each other.
An appropriate solution is to stop the previous Type() coroutine before you start a new one, like so:
Coroutine typeCoroutine = null;
public void NextSentenceGuitar()
{
if (index < sentences.Length - 1)
{
index++;
displayText.text = "";
if (typeCoroutine != null)
StopCoroutine(typeCoroutine);
typeCoroutine = StartCoroutine(Type());
}
else
{
displayText.text = "";
Canvas.SetActive(false);
}
}
IEnumerator Type()
{
foreach (char letter in sentences[index].ToCharArray())
{
displayText.text += letter;
yield return new WaitForSeconds(typingspeed);
}
typeCoroutine = null;
}
Thanks mchts, I think you are right, the lines are executed if I hold down the E button for too long. I am not exactly sure what your solution meant but I will try to figure it now. Would appreciate if you can provide a bit more information.