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文本实现打字机(一个一个出来)的效果

相关推荐
狂人开飞机4 小时前
21、游戏架构设计模式
游戏·游戏引擎·godot
新的瑞拉公主1 天前
Unity游戏发布微信小游戏:从构建到提审
unity·webgl·微信小游戏·开放数据域
狂人开飞机2 天前
14、游戏手感与视觉打磨
游戏·游戏引擎·godot
狂人开飞机2 天前
15、音频系统
游戏引擎·godot
狂人开飞机2 天前
16、粒子线条与视觉特效
游戏引擎·godot
心前阳光3 天前
Unity发布PC软件图标不能改变
unity·游戏引擎
an86950013 天前
unity如何在visual studio中打断点debug
unity·游戏引擎·visual studio
xcLeigh3 天前
Unity基础:使用Transform控制物体移动——Translate与position详解
unity·游戏引擎
FairGuard手游加固3 天前
Unity小游戏加密:global-metadata.dat与AssetBundle保护
游戏·unity·游戏引擎
狂人开飞机3 天前
11、UI系统
游戏引擎·godot