[Unity学习]使用ScrollRect实现自动滚动到底部显示实时消息,并在拖动的时候取消自动滚动,再次手动滑到底部,又继续自动滚动

首先需要重写ScrollRect组件:

using UnityEngine.UI;
using UnityEngine.EventSystems;

public class MScrollRect : ScrollRect
{
    
    
    public bool isDrag;
    public override void OnDrag(PointerEventData eventData)
    {
    
    
        base.OnDrag(eventData);
        isDrag = true;
    }

    public override void OnEndDrag(PointerEventData eventData)
    {
    
    
        base.OnEndDrag(eventData);
        if (normalizedPosition.y<=0)
        {
    
    
            isDrag = false;
        }
    }
}

下面通过协程实现在不滚动ScrollRect的时候,自动滚动到底部。

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

public static class UIHelper
{
    
    
 	public static void AddScrollText(Text prefab, RectTransform contentRoot, string text, MScrollRect scrollRect)
    {
    
    
        if (contentRoot == null)
            return;

        var listItem = GameObject.Instantiate<Text>(prefab, contentRoot, false);
        listItem.text=text;

        if (scrollRect != null && scrollRect.isActiveAndEnabled)
            scrollRect.StartCoroutine(ScrollToBottom(scrollRect));
    }

    public static IEnumerator ScrollToBottom(MScrollRect scrollRect)
    {
    
    
        yield return null;

        if (scrollRect != null && scrollRect.isActiveAndEnabled&&!scrollRect.isDrag)
            scrollRect.normalizedPosition = new Vector2(0, 0);
    }
}

 

使用时,写下面类似代码即可:

using UnityEngine;
using UnityEngine.UI;

public class AutoScrollTest : MonoBehaviour
{
    
    
    public Text textPrefab;
    public RectTransform contentRoot;
    public MScrollRect scrollRect;
    private float interval = 1;
    private float time=0;
    private void Update()
    {
    
    
        time += Time.deltaTime;
        if (time>=interval)
        {
    
    
            AddText();
            time = 0;
        }
    }

    public void AddText()
    {
    
    
        UIHelper.AddScrollText(textPrefab, contentRoot, time.ToString(), scrollRect);
    }
}

Unity原生Scroll View更改配置如下:
在这里插入图片描述
其中ScrollView游戏物体更改组件如下:
在这里插入图片描述
content配置如下:
在这里插入图片描述
实现效果如下:
在这里插入图片描述
大功告成!加上对象池模式控制添加的text实例效果会更好哦。

猜你喜欢

转载自blog.csdn.net/dong89801033/article/details/127016132
今日推荐