首先需要重写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);
}
}
使用时,写下面类似代码即可:文章来源:https://www.toymoban.com/news/detail-603566.html
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实例效果会更好哦。文章来源地址https://www.toymoban.com/news/detail-603566.html
到了这里,关于[Unity学习]使用ScrollRect实现自动滚动到底部显示实时消息,并在拖动的时候取消自动滚动,再次手动滑到底部,又继续自动滚动的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!