UGUI实现打字的效果

创建打字特效控制的脚本,将该脚本挂载都含有Text组件的对象上面,通过该脚本控制Text文本框的文字,以打字的效果显示文字。

脚本

using UnityEngine;
using System.Collections;
using UnityEngine.UI; public class TypewriterEffect : MonoBehaviour { public float charsPerSecond = 0.2f;//打字时间间隔 private string words;//保存需要显示的文字 private bool isActive = false; private float timer;//计时器 private Text myText; private int currentPos=0;  void Start () { timer = 0; isActive = true; charsPerSecond = Mathf.Max (0.2f,charsPerSecond); myText = GetComponent (); words = myText.text; myText.text = "";//获取Text的文本信息,保存到words中,然后动态更新文本显示内容,实现打字机的效果 }  void Update () { OnStartWriter ();  } public void StartEffect(){ isActive = true; } ///  /// 执行打字任务 ///  void OnStartWriter(){ if(isActive){ timer += Time.deltaTime; if(timer>=charsPerSecond){//判断计时器时间是否到达 timer = 0; currentPos++; myText.text = words.Substring (0,currentPos);//刷新文本显示内容 if(currentPos>=words.Length) { OnFinish(); } } } } ///  /// 结束打字,初始化数据 ///  void OnFinish(){ isActive = false; timer = 0; currentPos = 0; myText.text = words; } }

转载于:https://www.cnblogs.com/mengmengxia/p/8186004.html

你可能感兴趣的:(UGUI实现打字的效果)