Inconsistent GetMouseButtonDown Behaviour
Hi everyone! I've been easing my way into learning how to code game dialogue by advancing a simple dialogue stream with a mouse click. However, I'm finding that while my code works some of the time, it frequently does not detect the mouse click. Additionally, sometimes when the mouse click is not detected, Unity seems to store the event and trigger it two (or three) times the next time the mouse is clicked, making the dialogue unreadable.
I have already confirmed that this script is only acting on one gameobject. It is also using Text, not GUIText. I'm fairly new to Coroutines, so I suspect the problem is somewhere in there.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class prologueCode : MonoBehaviour {
public Text textBox, label;
public TextAsset dialogue;
string[] lines;
int i = 0;
public cameraFade cam;
bool firstTime = true;
public void Start()
{
if (dialogue != null)
{
lines = (dialogue.text.Split('\n'));
}
}
public void LateUpdate () {
if (firstTime)
{
cam.SetScreenOverlayColor(new Color(0, 0, 0, 1));
cam.StartFade(new Color(0,0,0,0), 7);
firstTime = false;
}
StartCoroutine(showDialogue());
}
IEnumerator showDialogue()
{
yield return new WaitForSeconds(7);
textBox.text = lines[i];
while (i < 9)
{
yield return StartCoroutine(waitClick());
textBox.text = lines[i];
i++;
}
}
IEnumerator waitClick()
{
while (!Input.GetMouseButtonDown(0))
{
yield return new WaitForEndOfFrame();
}
}
}
If it helps to know, sometimes the array index manages to exceed the loop limit and triggers an outOfBounds exception.
Thanks for all the help!
So it looks I've managed to solve it somehow. It's catching every mouseclick now and not doing that weird doubleclick thing. I ended up changing the showDialogue and waitClick routines to the following:
IEnumerator showDialogue()
{
yield return new WaitForSeconds(1f);
textBox.text = lines[i];
while (i <lines.Length-1)
{
yield return StartCoroutine(waitClick());
if (flag)
{
i++;
textBox.text = lines[i];
flag = false;
}
}
}
IEnumerator waitClick()
{
while (!Input.Get$$anonymous$$ouseButtonDown(0))
{
yield return 0;
}
flag = true;
yield return new WaitForEndOfFrame();
}
This works, but if any one knows a better way (or can explain why this works and the one before did not), I'm all ears!
Answer by justpassingby · Jun 08, 2016 at 02:38 PM
More information! You still need the "yield return new WaitForEndOfFrame();" function in the waitClick corountine, but it turns out the main problem was that I put StartCorountine in update instead of start. As far as I can tell, this made the Corountine start from the beginning in each frame instead of from the yield statement. I've been able to remove the flag boolean now.
Your answer
Follow this Question
Related Questions
Inserting specific words into descriptions stored in XML 0 Answers
Dialogue Skipping Issues? 0 Answers
How can I update my dialogue text? 0 Answers