这个脚本是来模拟一个键盘输入的效果,如下图
而且同样适用于英文,如图
主要实现是把当前的Text先存入一个变量中,然后往当前Text加随机某个字符到时间后再还原至之 前的Text,本人是业余选手,代码可能比较不规范。
//加入随机字符后重置为原来的字符
targetText.text += thisText[Random.Range(0, textNum)];
if (isNeedInputLine)
{
targetText.text += InputLine;
}
yield return new WaitForSeconds(randomTextPerTime);
参数有相应的解释,只需要将脚本挂到Text身上,并在Text文本框输入想有效果的内容即可
InputLineStatus--如果打开此选项,则会有输入线闪烁
InputLine--输入线的文本,建议为 |或者▐ ,当然其他的字符也是可行的
InputLinePerTime--每次输入线闪烁所需要的时间
RandomTimes--每个字出现之前所需要随机的次数
RandomTextPerTime--每次随机需要的时间
最后推荐几个看着比较舒服的参数 左边为中文 右边为英文
脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextEffectScripts : MonoBehaviour
{
private Text targetText;
private string thisText;
private int textNum;
private int textIndex;
private int textStaus;
private char textChar;
private bool textHaveFinished;
private bool isNeedInputLine;
private int textInputLine;
IEnumerator textEffectIEnumerator;
[Header("InputLineStatus/是否需要输入线滞留")]
public bool InputLineStatus;
[Header("InputLine/输入线文本不需要留空")]
public string InputLine;
[Header("InputLinePerTime/输入线闪烁时间")]
public float InputLineTime;
[Header("RandomTimes/每字体所需随机次数")]
[Range(0,20)]
public int randomTimes;
[Header("RandomTextPerTime/每字体所需随机时间")]
[Range(0, 1)]
public float randomTextPerTime;
private string thisTextBefore;
// Start is called before the first frame update
void Start()
{
textEffectIEnumerator = TimerTextEffect();
if (InputLine == string.Empty)
{
isNeedInputLine = false;
}
else if(InputLine.Trim() != string.Empty)
{
isNeedInputLine = true;
}
targetText = this.GetComponent<Text>();
thisText = targetText.text;
textNum = thisText.Length;
targetText.text = string.Empty;
thisTextBefore = string.Empty;
StartCoroutine(textEffectIEnumerator);
}
IEnumerator TextInputLineIEnumerator()
{
while (true)
{
textInputLine++;
if (textInputLine == 1)
{
targetText.text += InputLine;
}
else if(textInputLine == 2)
{
targetText.text = thisTextBefore;
}
else
{
textInputLine = 0;
}
yield return new WaitForSeconds(InputLineTime);
}
}
IEnumerator TimerTextEffect()
{
while (!textHaveFinished)
{
//判断循环次数
textStaus++;
if (textStaus != randomTimes+1)
{
targetText.text = thisTextBefore;
}
targetText.text = thisTextBefore;
if (textStaus <= randomTimes)
{
//加入随机字符后重置为原来的字符
targetText.text += thisText[Random.Range(0, textNum)];
if (isNeedInputLine)
{
targetText.text += InputLine;
}
yield return new WaitForSeconds(randomTextPerTime);
}
else
{
if (textIndex != textNum)
{
targetText.text += thisText[textIndex];
textStaus = 0;
thisTextBefore = targetText.text;
textIndex++;
if (randomTimes == 0)
{
yield return new WaitForSeconds(randomTextPerTime);
}
}
else
{
if (isNeedInputLine)
{
if (InputLineStatus)
{
StartCoroutine(TextInputLineIEnumerator());
}
}
textHaveFinished=true;
yield break;
//结束字体效果
}
}
}
}
}
只需要复制然后挂到Text脚本上即可使用。
最后这是Github地址:
https://github.com/WeekenicX/UnityTextEInputEffect
谢谢您看到最后,如果有问题欢迎提出来。