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

public class Typewriter : MonoBehaviour
{
    /// <summary>
    /// 打字速度 
    /// </summary>
    public float TypeSpeed = 0.2f;

    public Text Showtext;

    /// <summary>
    /// 文本内容字符串
    /// </summary>
    public string StringContent = "";

    /// <summary>
    /// 当前文字位置（当前的最后一个字）
    /// </summary>
    private int curPos;

    void Awake()
    {
        Showtext = this.GetComponent<Text>();
    }

    private void Start()
    {
    }

    [ContextMenu("SetContent")]
    /// <summary>
    /// 设置内容
    /// </summary>
    public void SetContent()
    {
        StringContent = Showtext.text;
        curPos = 0;
        Debug.Log("文本内容：" + StringContent.Length);
        Showtext.text = string.Empty;
        InvokeRepeating("Typing", 0, TypeSpeed);
    }

    public void Pause()
    {
        CancelInvoke("Typing");
    }

    void Typing()
    {
        if (StringContent.Length - 1 == curPos) //如果当前字符位置等于字符总长度前一个位置就停止调用打字方法
            CancelInvoke("Typing");


        if (curPos < StringContent.Length)
        {
            Showtext.text += StringContent.Substring(curPos, 1); //每次都截取到当前位置的下一个字符位置
            curPos++;
        }
    }
}