首先需要重写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实例效果会更好哦。