- Home /
How can I clear a textbox and repeat the text with my effect?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Title : MonoBehaviour
{
public string textShownOnScreen;
public Text textBox;
public string fullText = "The Arcade";
public float wordsPerSecond = 2; // speed of typewriter
private float timeElapsed = 0;
void Update()
{
timeElapsed += Time.deltaTime;
textShownOnScreen = GetWords(fullText, timeElapsed * wordsPerSecond);
}
private string GetWords(string text, float wordCount)
{
float words = wordCount;
// loop through each character in text
for (int i = 0; i < text.Length; i++)
{
words--;
textBox.text = textShownOnScreen;
if (words <= 0)
{
return text.Substring(0, i);
}
}
return text;
}
}
Is there a way to loop this? I want it to repeat over and over but can't fathom a way to do it.
Comment
Are you saying that once the effect finishes, you want the text to disappear and the effect to start again?
Yes. I tried a coroutine, but it started to freak out and repeat it over and over until it crashed. I might not have been executing it right. But if I tried to stop it, then it would never start again.
public string textShownOnScreen;
public Text textBox;
public string fullText;
public float wordsPerSecond;
private float timeElapsed;
int letterIndex;
void Start(){
letterIndex = 0;
timeElapsed = 0;
wordsPerSecond = 2; // speed of typewriter
fullText = "The Arcade";
}
void Update()
{
timeElapsed += Time.deltaTime;
if(timeElapsed >= 1/wordsPerSecond && letterIndex < fullText.Length) {
letterIndex++;
textShownOnScreen = fullText.Substring(0, letterIndex);
textBox.text = textShownOnScreen; //display textShownOnScreen
timeElapsed = 0; //reset timer to get next fullText state
}
}