Skip to content

Instantly share code, notes, and snippets.

@daleth90
Last active July 11, 2016 14:24
Show Gist options
  • Save daleth90/9dbe2880d5fc3c1db4b3fdb86f027384 to your computer and use it in GitHub Desktop.
Save daleth90/9dbe2880d5fc3c1db4b3fdb86f027384 to your computer and use it in GitHub Desktop.
using System;
public interface TextDisplayer {
void Show();
void Hide();
void RegisterOnRequestNextDialog( Action method );
void SetText( string text );
}
using UnityEngine;
using UnityEngine.UI;
using System;
public class TextTyperDisplayer : MonoBehaviour, TextDisplayer {
[SerializeField]
private Text dialog;
[SerializeField]
private Button clickMask;
[SerializeField]
[Range( 0.01f, 0.5f )]
private float typeTime = 0.02f;
private string wholeDialog = string.Empty;
private int currentCharacterIndex;
private float timer;
private Action onRequestNextDialog = delegate { };
private void Awake() {
clickMask.onClick.AddListener( OnClick );
}
private void Update() {
if ( IsTyping() ) {
timer += Time.deltaTime;
if ( timer >= typeTime ) {
++currentCharacterIndex;
dialog.text = wholeDialog.Substring( 0, currentCharacterIndex );
timer = 0f;
}
}
}
private void OnClick() {
if ( IsTyping() ) {
currentCharacterIndex = wholeDialog.Length;
dialog.text = wholeDialog.Substring( 0, currentCharacterIndex );
}
else {
onRequestNextDialog.Invoke();
}
}
private bool IsTyping() {
return currentCharacterIndex < wholeDialog.Length;
}
#region TextDisplayer implementation
public void Show() {
gameObject.SetActive( true );
}
public void Hide() {
gameObject.SetActive( false );
}
public void RegisterOnRequestNextDialog( Action method ) {
onRequestNextDialog = method;
}
public void SetText( string text ) {
wholeDialog = text;
currentCharacterIndex = 0;
timer = 0f;
dialog.text = string.Empty;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment