Unity UGUI技巧 之 Text文字实现打印机效果
1、String.subString(start,end):
截取的字符串包括起点所在的字符串
2、方法提示:
1)获取Text的文本内容
2)计时器时间间隔
3)String.subString(start,end)实现对应文本内容显示
1、打开Unity,新建一个空工程,具体如下图

2、在场景中,添加“Text”,并填写内容,调整“Text”布局,具体如下图

3、新建脚本“TyperTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下

4、在打开的脚本“TyperTest”上编辑代码,具体的代码和代码说明如下图



5、“TyperTest”脚本的具体内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TyperTest : MonoBehaviour {
public float charsPerSeconds = 0.2f;
private string content;
private Text textTest;
private float timer;
private int currentPos;
private bool isActive;
// Use this for initialization
void Start () {
textTest = GetComponent <Text> ();
content = textTest.text;
textTest.text = "";
charsPerSeconds = Mathf.Max (0.2f, charsPerSeconds);
timer = charsPerSeconds;
isActive = false;
currentPos = 0;
}
// Update is called once per frame
void Update () {
if (isActive == true){
StartTyperEffect ();
}
}
public void TyperEffect(){
isActive = true;
}
private void StartTyperEffect() {
timer += Time.deltaTime;
if (timer > charsPerSeconds) {
timer -= charsPerSeconds;
currentPos++;
textTest.text = content.Substring (0, currentPos);
if(currentPos >= content.Length) {
FinishTyperEffect ();
}
}
}
private void FinishTyperEffect() {
isActive = false;
timer = charsPerSeconds;
currentPos = 0;
textTest.text = content;
}
}
6、脚本编译正确,回到Unity界面,把脚本添加“Text”上,在新建一个脚本“ToCallTyperEffect”,具体如下图

7、在脚本“ToCallTyperEffect”上编辑代码,首先获取脚本“TyperTest”,然后调用脚本“TyperTest”的函数“TyperEffect”,具体的代码和代码说明如下图

8、“ToCallTyperEffect”脚本的具体内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ToCallTyperEffect : MonoBehaviour {
public TyperTest typerTest;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.T)){
if(typerTest == null){
return;
}
typerTest.TyperEffect ();
}
}
}
9、脚本编译正确后,回到Unity界面,新建一个“GameObject”,把脚本“ToCallTyperEffect”赋给“GameObject”,把“Text”赋给脚本“ToCallTyperEffect”,具体如下图

10、运行场景,按下“T”键,文字打印机效果出现,具体如下图

11、到此,《Unity UGUI技巧 之 Text文字实现打印机效果》讲解结束,谢谢