【Unity3d】如何实现自动滚动文本效果

       当我们在制作UI使用Text时,如果文本信息过长,有两种处理方式,一种是换行展示,另一种则是滚动展示,下面博主将给大家介绍如何制作自动滚动文本。

       第一步,创建一个Image(GameObject > UI > Image),可以看到出现了一个白色的框框,改变框框的尺寸,以便进行文本信息显示,接着在Image下创建一个Text(GameObject > UI > Iegacy > Text),改变Text的尺寸,长度超出Image尺寸或边界,可以将Image改为半透明,初始化文本信息“Success is the ability to go from one failure to another with no loss of enthusiasm.”,属性根据自己进行设置,如下图所示。

       第二步,为Image添加组件Mask,效果如上图,再添加组件Scroll Rect,进行设置如下图,将Text拖入,Horizontal是横向滚动,Vertical是纵向滚动,这里我们取消Vertical,Movement Type(下面会进行介绍)设置为Clamped(可拖拽,无弹性)。

       属性Movement Type介绍:

               Unrestricted:无限制,可任意拖拽,可超出文本边界。

               Elastic:可拖拽,有弹性,不可超出文本边界。

               Clamped:可拖拽,无弹性,不可超出文本边界。

       第三步,给Image贴代码,新建C#文件,重命名为TextController,双击打开cs文件,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextController : MonoBehaviour
{
    public ScrollRect rect;
    // Start is called before the first frame update
    void Start()
    {
        rect = gameObject.GetComponent<ScrollRect>();//绑定组件
    }

    // Update is called once per frame
    void Update()
    {
        rect.horizontalNormalizedPosition += 0.08f * Time.deltaTime;//滚动速度
    }
}

       以上,一个简单的自动文本滚动效果就做好了,运行即可。

       下面再给大家介绍下在博主的3d游戏项目案例(金山打字之生死时速)中如何控制滚动效果和玩家打字的速率同步,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextController : MonoBehaviour
{
    public ScrollRect rect;
    // Start is called before the first frame update
    void Start()
    {
        rect = gameObject.GetComponent<ScrollRect>();
    }

    // Update is called once per frame
    void Update()
    {
        //rect.horizontalNormalizedPosition += 0.08f * Time.deltaTime;
    }
    public void Run()
    {
        rect.horizontalNormalizedPosition += 0.02f;//滚动频率
    }
}

       在原文PlayerController.cs文件中判断是否按下字母函数下加入以下代码实现调用:

    if (index >= 9)//当敲第10个字母的时候,开始滚动
    {
       runText.GetComponent<TextController>().Run();//调用函数
    }

猜你喜欢

转载自blog.csdn.net/m0_51942776/article/details/127716098