P
P
Pickto2017-03-05 06:34:00
C++ / C#
Pickto, 2017-03-05 06:34:00

Letter-by-letter text typing in Unity and UI?

How to display text on the UI screen using coroutines.
Here is the code, but it has an error, I can not figure out how to fix it

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class dialog : MonoBehaviour {
  public bool skipText;
  private bool isPrint;
  public static string textMess;

  public GameObject dialogField;


  // Use this for initialization
  void Start () {
    StartCoroutine(TextPrint(dialogField.GetComponent<Text>().text, textMess, 0.1f, skipText));
    isPrint = false;
  }
  
  // Update is called once per frame
  void Update () {
    
    
  }

    
  IEnumerator TextPrint(string output, string input, float delay, bool skip)
  {
 		if (isPrint) yield break;
 		isPrint = true;
    //вывод текста побуквенно
 		for (int i=1; i<=input.Length; i++) {
  			if (skip) { output = input; break; }
  		output = input.Substring(1, i);
  		yield return new WaitForSeconds(delay);
 		}
 	}
 	

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pparma, 2017-03-05
@Pickto

You have a new coroutine launched on each update and each one starts to display text. At least remove isPrint = false from the update. Better yet, change the logic so as not to run the coroutine in every update.

StartCoroutine(TextPrint(dialogField.GetComponent<Text>(), textMess, 0.1f, skipText));

IEnumerator TextPrint(Text output, string input, float delay, bool skip)
{ 
...
output.text = input.Substring(0, i);
...
}

By the way, the string indexes start from zero, not from one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question