Unity小功能

文章介绍了三个Unity脚本,分别使用不同的方法实现文本逐字显示的打字效果:第一个脚本使用计时器和字符串操作,第二个脚本利用协程,第三个脚本借助DG.Tweening库。
摘要由CSDN通过智能技术生成

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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值