0


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

  1. 当我们在制作UI使用Text时,如果文本信息过长,有两种处理方式,一种是换行展示,另一种则是滚动展示,下面博主将给大家介绍如何制作自动滚动文本。
  2. 第一步,创建一个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.”,属性根据自己进行设置,如下图所示。

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

  1. 属性Movement Type介绍:
  2. Unrestricted:无限制,可任意拖拽,可超出文本边界。
  3. Elastic:可拖拽,有弹性,不可超出文本边界。
  4. Clamped:可拖拽,无弹性,不可超出文本边界。
  5. 第三步,给Image贴代码,新建C#文件,重命名为TextController,双击打开cs文件,代码如下:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TextController : MonoBehaviour
  6. {
  7. public ScrollRect rect;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. rect = gameObject.GetComponent<ScrollRect>();//绑定组件
  12. }
  13. // Update is called once per frame
  14. void Update()
  15. {
  16. rect.horizontalNormalizedPosition += 0.08f * Time.deltaTime;//滚动速度
  17. }
  18. }
  1. 以上,一个简单的自动文本滚动效果就做好了,运行即可。
  2. 下面再给大家介绍下在博主的3d游戏项目案例(金山打字之生死时速)中如何控制滚动效果和玩家打字的速率同步,代码如下:
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TextController : MonoBehaviour
  6. {
  7. public ScrollRect rect;
  8. // Start is called before the first frame update
  9. void Start()
  10. {
  11. rect = gameObject.GetComponent<ScrollRect>();
  12. }
  13. // Update is called once per frame
  14. void Update()
  15. {
  16. //rect.horizontalNormalizedPosition += 0.08f * Time.deltaTime;
  17. }
  18. public void Run()
  19. {
  20. rect.horizontalNormalizedPosition += 0.02f;//滚动频率
  21. }
  22. }
  1. 在原文PlayerController.cs文件中判断是否按下字母函数下加入以下代码实现调用:
  1. if (index >= 9)//当敲第10个字母的时候,开始滚动
  2. {
  3. runText.GetComponent<TextController>().Run();//调用函数
  4. }
标签: unity 游戏引擎 ui

本文转载自: https://blog.csdn.net/m0_51942776/article/details/127716098
版权归原作者 樱花不再在海棠湾涮羊肉 所有, 如有侵权,请联系我们删除。

“【Unity3d】如何实现自动滚动文本效果”的评论:

还没有评论