using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class TypeWrite : MonoBehaviour {
private string content;//要打印的内容
private long length;//打印内容长度
public Text text;//UGUIText组件
enum PrintState
{
None,
Start,
Continue,
Stop,
Restart,
Ining,
Repeat
}
private PrintState state = PrintState.None;
// Use this for initialization
void Start () {
//如果已经初始化赋值
if (text!=null)
{
//将要出现打字机效果的内容写在text组件里面
content = text.text;//得到打印内容
length = content.Length;//获取内容长度
text.text = "";//清空默认显示
}
}
//开始打印按钮
public void StartPrint()
{
if (state==PrintState.Stop)
{
state = PrintState.Continue;
}
//保证只会执行一次
if (state==PrintState.None)
{
state = PrintState.Start;
//保证打印完不会重复执行
if (i < length)
{
//开启打印协程
StartCoroutine(Wait());
}
}
//继续打印
if (state ==PrintState.Continue)
{
state = PrintState.Ining;
i = i + 1;
//保证打印完不会重复执行
if (i < length)
{
//开启打印协程
StartCoroutine(Wait());
}
}
//再次打印
if (state == PrintState.Repeat)
{
i = 0;
//保证打印完不会重复执行
if (i < length)
{
//开启打印协程
StartCoroutine(Wait());
}
}
}
//停止打印按钮
public void Stop()
{
StopAllCoroutines();
state = PrintState.Stop;
}
//重新打印按钮
public void Restart()
{
if (i!=0)
{
StopAllCoroutines();//保证是完全重新开始
state = PrintState.Restart;
i = 0;
text.text = "";
//保证打印完不会重复执行
if (i < length)
{
//开启打印协程
StartCoroutine(Wait());
}
}
}
// Update is called once per frame
void Update () {
//按下空格开始执行打字机效果
if (Input.GetKeyDown(KeyCode.Space))
{
//保证打印完不会重复执行
if (i<length)
{
//开启打印协程
StartCoroutine(Wait());
}
}
}
int i = 0;//打印内容起点
public float speed = 0.2f;//打字机速度
IEnumerator Wait()
{
//退出协程条件
if (i>length-1)
{
state = PrintState.Repeat;
yield break;//退出协程
}
text.text += content[i];//逐渐打印内容
yield return new WaitForSeconds(speed);//等待
i++;//打印下一个字符
StartCoroutine(Wait());//继续调用协程
}
}
UGUI打印机效果升级版
最新推荐文章于 2024-04-01 23:18:07 发布