Hi, i’m trying to make a script that displays any given text character by character, so far I’ve got this:
using UnityEngine.UI;
public class textScript : MonoBehaviour {
public Text textComponent;
public string text;
public float timeCounter;
public float timeLapse;
void Update ()
{
timeCounter += Time.deltaTime;
for (int i = 0; i < text.Length; i++) {
if (timeCounter >= timeLapse) {
textComponent.text = string.Concat (textComponent.text, text *);*
-
timeCounter = 0;*
-
}*
-
}*
- }*
}
But it just concatenate the first character of the string over and over… it doesn’t even stop when it reaches the text.Length condition in the for. Could somebody explain at least why is this happening?
You’re probably looking for something like this:
void Start(){
StartCoroutine(BuildText());
}
private IEnumerator BuildText(){
for (int i = 0; i < text.Length; i++){
textComponent.text = string.Concat(textComponent.text, text*);*
//Wait a certain amount of time, then continue with the for loop
yield return new WaitForSeconds(timeLapse);
}
}
With your code, the for loop is executed on every single update. Every time you concatenate the strings, you reset the timer to zero. The next time the timer is ready, the for loop is at the beginning again and so you end up concatenating the first character again.
You need to trace which character you’re typing, like this:
private int currentCharacterIndex;
private void Update() {
if ( IsTyping() ) {
timer += Time.deltaTime;
if ( timeCounter >= timeLapse ) {
++currentCharacterIndex;
textComponent.text = wholeDialog.Substring( 0, currentCharacterIndex );
timer = 0f;
}
}
}
private bool IsTyping() {
return currentCharacterIndex < wholeDialog.Length;
}
You can still use string.Concat, I just prefer to use Substring in this case.