- Home /
Question by
MrYadaization · Nov 15, 2015 at 10:17 AM ·
c#scripting problemtext
Continuous autotype script?
I'm looking for something to what I am using below (You've all probably seen the below code before), but that waits for a button press to continue to a line if the text is too long, and a way to recognize when all text has been displayed.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class AutoType : MonoBehaviour {
public float letterPause = 0.2f;
private Text text;
string message;
void Start()
{
text = GetComponent<Text>();
message = text.text;
text.text = "";
StartCoroutine(TypeText());
}
IEnumerator TypeText()
{
foreach (char letter in message.ToCharArray())
{
text.text += letter;
gameObject.GetComponent<AudioSource>().Play();
yield return 0;
yield return new WaitForSeconds(letterPause);
}
}
}
This is my first time posting here so sorry if I've done something wrong.
Comment
Best Answer
Answer by Jessespike · Nov 15, 2015 at 12:28 PM
There might be a way to check if the message doesn't fit in the UI.Text, but I'm not sure how. So here I'm simply counting the number of chars in the message.
I changed the foreach-loop to a for-loop.
Created a function that determines if the message being displayed is full, you'll want to rewrite or expand on this.
Also created a coroutine that will wait for user input.
// A coroutine that will loop until a key is pressed IEnumerator WaitForInput() { while (!Input.anyKey) { yield return null; } yield return null; } //Determines if message will fit //TODO: return true if last word in message exceeds limit bool IsDisplayMessageFull(int i) { int maxLettersToShow = 8; if (i != 0 && i % maxLettersToShow == 0) return true; return false; } IEnumerator TypeText() { for (int i = 0; i < message.ToCharArray().Length; i++) { if (IsDisplayMessageFull(i)) { yield return StartCoroutine(WaitForInput()); text.text = ""; } text.text += message.ToCharArray()[i]; gameObject.GetComponent<AudioSource>().Play(); yield return new WaitForSeconds(letterPause); } }
Your answer
![](https://koobas.hobune.stream/wayback/20220612045124im_/https://answers.unity.com/themes/thub/images/avi.jpg)