首先需要重寫(xiě)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;
}
}
}
下面通過(guò)協(xié)程實(shí)現(xiàn)在不滾動(dòng)ScrollRect的時(shí)候,自動(dòng)滾動(dòng)到底部。
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);
}
}
使用時(shí),寫(xiě)下面類(lèi)似代碼即可:文章來(lái)源:http://www.zghlxwxcb.cn/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配置如下:
實(shí)現(xiàn)效果如下:
大功告成!加上對(duì)象池模式控制添加的text實(shí)例效果會(huì)更好哦。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-603566.html
到了這里,關(guān)于[Unity學(xué)習(xí)]使用ScrollRect實(shí)現(xiàn)自動(dòng)滾動(dòng)到底部顯示實(shí)時(shí)消息,并在拖動(dòng)的時(shí)候取消自動(dòng)滾動(dòng),再次手動(dòng)滑到底部,又繼續(xù)自動(dòng)滾動(dòng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!