Unity_实现文字打字效果(转载)

原文地址:

https://blog.csdn.net/Delesgues/article/details/88170710

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

public class TypewriterEffect : MonoBehaviour
{

	public float charsPerSecond = 0.2f;//打字时间间隔
	public string words;//保存需要显示的文字

	public bool isActive = false;
    public float timer;//计时器
    public Text myText;
    public int currentPos = 0;//当前打字位置

	// Use this for initialization
	void Start()
	{
		timer = 0;
		isActive = true;
		charsPerSecond = Mathf.Max(0.2f, charsPerSecond);
		myText = GetComponent<Text>();
		words = myText.text;
		myText.text = "";//获取Text的文本信息,保存到words中,然后动态更新文本显示内容,实现打字机的效果
	}

	// Update is called once per frame
	void Update()
	{
		OnStartWriter();
		//Debug.Log (isActive);
	}

	public void StartEffect()
	{
		isActive = true;
	}
	/// <summary>
	/// 执行打字任务
	/// </summary>
	void OnStartWriter()
	{

		if (isActive)
		{
			//timer += Time.deltaTime;
			timer += 0.5f;   //打字的速度 timer += 1f;
			if (timer >= charsPerSecond)
			{//判断计时器时间是否到达
				timer = 0;
				currentPos++;
				myText.text = words.Substring(0, currentPos);//刷新文本显示内容

				if (currentPos >= words.Length)
				{
					OnFinish();
				}
			}

		}
	}
	/// <summary>
	/// 结束打字,初始化数据
	/// </summary>
	void OnFinish()
	{
		isActive = false;
		timer = 0;
		currentPos = 0;
		myText.text = words;
	}


    private void OnEnable()
    {
        isActive = true;
    }

    private void OnDisable()
    {

    }



}

猜你喜欢

转载自blog.csdn.net/weixin_42137574/article/details/103763505