不得不说,在敲代码的过程当中一定要有一个面向对象的思想,还有一定不要钻牛角尖,这条路行不通就换条路去走。
废话不多说了,就直接上代码吧!
在做的过程当中,需要把文字及其他的背景当做一个对象,有消息来就创建这个对象让他滚动,在创建之前一定要记得清除一下:
以下我只赋上对象滚动的代码:
using DG.Tweening;
using Hades.Proto.Com;
using Hades.Ui.Comm;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
namespace Hades.UI.Home
{
class ImageBgWidget : Widget
{
private Queue<string> _MsgQueue;//在创建这个对象的时候传过来的参数赋到这里。
private Text _textLamp;
private float _beginX;
private float _leftX;
private float _speed;
private float _txtWidth;
private float _distance;
private float _duration;
private void Awake()
{
_textLamp = transform.Find("TextLamp").GetComponent<Text>();
if(gameObject.activeSelf==false)
{
gameObject.SetActive(true);
}
}
public void Init(Queue<string> MsgQueue)
{
_MsgQueue = MsgQueue;
}
protected override void Start()
{
base.Start();
_beginX = 100;
_duration = 5f;
_speed = 60f;
_txtWidth = _textLamp.preferredWidth;//文本自身的长度.
_leftX =- _txtWidth-150;
_distance = _beginX - _leftX + _txtWidth;
_duration = _distance / _speed;
if (_MsgQueue != null)
{
string msg = _MsgQueue.Dequeue();//Queue 队列 先入先出==》Dequeue出栈
_textLamp.text = msg;
}
StartCoroutine(ScrollText());
}
IEnumerator ScrollText()
{
float loop = 1;
while (loop-- > 0)
{
Vector3 pos = _textLamp.rectTransform.localPosition;
_textLamp.rectTransform.localPosition = new Vector3(_beginX, pos.y, pos.z);
_textLamp.rectTransform.DOLocalMoveX(-_distance, _duration).SetEase(Ease.Linear);
yield return new WaitForSeconds(_duration);
}
gameObject.SetActive(false);
yield break;
}
}
}
有问题在下方评论就可以啦