Unity中使用脚本实现打字机效果cs
2022-06-15 本文已影响0人
荼蘼toome
在有文字提示的时候,想要实现一个字一个字的往外面提示,
下面来介绍一下实现方式


方法一 使用计时器
TypewriterEffect .cs脚本
using UnityEngine;
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;//当前打字位置
// 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;
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;
}
}
方法二 使用DoTween插件
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class DoTxt : MonoBehaviour
{
public Text TxtTips;//text组件
public string str;//文字
public float time;//显示时间
//想要首航缩进的话,空格不好用
//①复制 这是两个空白的字符,需要的自行复制
//②在脚本中直接赋值text是最简单的
//TextTest.text =“\u3000\u3000”+"字符串";
//2.UGUI的Text如果在编辑器直接输入显示我们可以自定义某几个字符串的alpha值
// <color=#FFFFFF00>-----</color>
void Start()
{
TxtTips.DOText(str,time).SetEase(Ease.Linear);//匀速显示当前文章
}
}
```
### 方法三
```
private float letterPause = 0.2f;//等待时间
private string str;
public Text TxtTips;
public Text TxtTitle;
private IEnumerator TypeText(string text, Text txt)
{
_Introduce.clip = BgClips;//打字声音
str = "";
foreach (char letter in text.ToCharArray())
{
str += letter;
//if (BgClips && !_Introduce.isPlaying)
//{
// _Introduce.Play ();
//}
yield return new WaitForSeconds(letterPause);
txt.text = str + "|";
_Introduce.Stop();//打字声音暂停
}
txt.text = text;
}
```