1. 将此脚本挂载到赋予好文本的Text中即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//没有这一行的话private Text myText;会报错
public class Typewriter: MonoBehaviour
{
public float a = 0.2f;//打字间隔时间
private string words;//文本
private bool isA = false;
private float timer;//时间
private Text myText;//text
private int b = 0;//一开始的字数
// Start is called before the first frame update
void Start()
{//一开始时间等于0,点击运行后开始打字,text读取组件中的text,文本就等于text组件text;
timer = 0;
isA = true;
myText = GetComponent<Text>();
words = myText.text;
myText.text = "";
}
// Update is called once per frame
void Update()
{
One();//当字数b大于文本字数时停止
}
void One()
{
if (isA)
{
timer += Time.deltaTime;//时间等于实时时间不断叠加;
if (timer >= a)//当时间大于等于打字间隔时间时;
{
timer = 0;//时间为0;
b++;//字数增加
myText.text = words.Substring(0, b);//text组件text中的字数等于文本字数;
if (b >= words.Length)//字数大于等于文字字数
{
Two();
}
}
}
}
void Two()
{
isA = false;//结束
timer = 0;//时间归0;
b = 0;//字数归0;
myText.text = words;//text等于文本;
}
}
2.将此脚本挂载到Text中即可。该脚本使用了协程。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Typewriter: MonoBehaviour
{
Text ShowTxet;
string ShowSte;
// Start is called before the first frame update
void Start()
{
ShowTxet = GetComponent<Text>();
ShowSte = "这是打字机***********************************************";
StartCoroutine(TypeText());
}
private IEnumerator TypeText()
{
foreach(var item in ShowSte .ToCharArray())
{
ShowTxet.text += item;
yield return new WaitForSeconds(0.5f);
}
}
3.将此脚本挂载到Text中即可。该脚本使用了DG.Tweening中的DOText,数字9为打字时长。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
public class Typewriter: MonoBehaviour
{
public Text mytext;
void Start()
{
mytext.DOText("这是打字机********",9);
}
}