Unity Text文本实现打字机(一个一个出来)的效果

Unity Text文本要实现打字机,即一个个文字出来的效果,可以通过代码把text文本字符串拆成一个个字符然后添加到文本中。

具体实现:

新建一个控制脚本:TypewriteController.cs,并编写以下代码:

复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class TypewriteController : MonoBehaviour
{
    public float typingSpeed = 0.1f; // 每个字符的显示间隔时间
    private string fullText;
    private string currentText = "";
    public Text textComponent;


    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            fullText = textComponent.text;
            textComponent.text = "";
            StartCoroutine(TypeText());
        }
    }

    IEnumerator TypeText()
    {
        foreach (char c in fullText)
        {
            currentText += c;
            textComponent.text = currentText;
            yield return new WaitForSeconds(typingSpeed);
        }
    }
}

此控制脚本先把脚本文本获取后赋给一个字符串变量,然后置空文本内容,再通过协程把该字符串变量值拆分成一个个字符,然后使用协程来把一个个字符(即单个文字) 赋值给文本,这样就完成了打字机的效果。

新建一个场景,并在场景创建一个Text组件,把脚本拉到场景中,再把Text组件拖到脚本中的textComponent对象,运行场景,效果如下:

Unity Text文本实现打字机(一个一个出来)的效果

相关推荐
妙为3 小时前
unreal engine5角色把敌人 “挤飞”
游戏引擎·虚幻·ue·unrealengine5
4Forsee3 小时前
【增强现实】快速上手 Vuforia Unity Android AR 应用开发
android·unity·ar
两水先木示3 小时前
【Unity】对指定物体进行描边——模板测试法
unity·游戏引擎·shader·外描边
Miss_SQ4 小时前
实现Unity录音、百度云语音转文字
unity·语音识别
CreasyChan4 小时前
unity 对象池实测可用
unity·c#
weixin_424294674 小时前
Unity项目的Artifacts文件夹过大怎么解决?
unity·游戏引擎
没事写写笔记12 小时前
Unity HDRP14.0.12 Volume 配置参数
unity
红黑色的圣西罗15 小时前
手游手动异形屏适配方案,类“明日方舟”
unity
syker1 天前
3D游戏引擎Bluely Engine 开发手册
开发语言·3d·游戏引擎
Longyugxq2 天前
Untiy的Webgl端网页端视频播放,又不想直接mp4格式等格式的。
unity·音视频·webgl