Skip to content

Instantly share code, notes, and snippets.

@reidscarboro
Created August 14, 2021 21:22
Show Gist options
  • Save reidscarboro/cb756e018d84202d1b3dca2eb692238e to your computer and use it in GitHub Desktop.
Save reidscarboro/cb756e018d84202d1b3dca2eb692238e to your computer and use it in GitHub Desktop.
public class TypewriterEffect : MonoBehaviour
{
public TextMeshProUGUI textMesh;
public float typeSpeed = 0.025f;
public Action OnTypewriterCompleted;
private int currentCursorLocation = 0;
public void SetText(string text)
{
textMesh.text = text;
textMesh.maxVisibleCharacters = 0;
}
public void SetTextImmediate(string text)
{
textMesh.text = text;
currentCursorLocation = textMesh.textInfo.characterCount;
textMesh.maxVisibleCharacters = currentCursorLocation;
}
public void PlayText()
{
currentCursorLocation = 0;
StartCoroutine(Play());
}
public void CompleteText()
{
StopCoroutine(Play());
currentCursorLocation = textMesh.textInfo.characterCount;
textMesh.maxVisibleCharacters = currentCursorLocation;
}
public bool IsPlaying()
{
return currentCursorLocation < textMesh.textInfo.characterCount;
}
private IEnumerator Play()
{
yield return new WaitForSeconds(typeSpeed);
while (currentCursorLocation < textMesh.textInfo.characterCount)
{
currentCursorLocation++;
textMesh.maxVisibleCharacters = currentCursorLocation;
yield return new WaitForSeconds(typeSpeed);
}
OnTypewriterCompleted?.Invoke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment