Unity3D ScrollView loop scrolling playback
First create a ScrollView on the UI,
mount the script on Content, and assign the ScrollView to the Parent.
Scrolling starts when the height of Content is greater than the capacity height of ScrollView.
The following is the script code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProfileContentRoll : MonoBehaviour
{
/// <summary>
/// 内容区域RectTransform
/// </summary>
private RectTransform rect;
/// <summary>
/// ScrollView
/// </summary>
public GameObject Parent;
/// <summary>
/// ScrollView的RectTransform
/// </summary>
private RectTransform parentRect;
/// <summary>
/// 起始Y值
/// </summary>
private float rectOriginY;
/// <summary>
/// 滚动速度
/// </summary>
private const float rollSpeed = 30;
/// <summary>
/// 是否底部
/// </summary>
private bool isAtBottom = false;
/// <summary>
/// 是否滚动
/// </summary>
private bool isRoll = true;
/// <summary>
/// 能否运行协程
/// </summary>
private bool canStartCoroutine = true;
/// <summary>
/// 内容高度是否大于窗口高度
/// </summary>
private bool isContentBiggerThanView = false;
/// <summary>
/// 等待时间
/// </summary>
private int waitTime = 5;
// Start is called before the first frame update
void Start()
{
rect = GetComponent<RectTransform>();
parentRect = Parent.GetComponent<RectTransform>();
rectOriginY = rect.position.y;
}
// Update is called once per frame
void Update()
{
isContentBiggerThanView = rect.sizeDelta.y > parentRect.sizeDelta.y;
isAtBottom = rect.position.y - rectOriginY >= rect.sizeDelta.y - parentRect.sizeDelta.y;
//如果滚动到底,运行协程
if(isAtBottom && isRoll && canStartCoroutine && isContentBiggerThanView)
{
canStartCoroutine = false;
StartCoroutine(StopAndBack());
}
//滚动
if (isRoll && isContentBiggerThanView)
{
rect.position = new Vector3(rect.position.x, rect.position.y + rollSpeed * Time.deltaTime, 0);
}
}
/// <summary>
/// 返回顶部
/// </summary>
private void BackToTop()
{
rect.position = new Vector3(rect.position.x, rectOriginY, 0);
}
IEnumerator StopAndBack()
{
isRoll = false;
//结尾停
yield return new WaitForSeconds(waitTime);
BackToTop();
//开头停
yield return new WaitForSeconds(waitTime);
isRoll = true;
canStartCoroutine = true;
}
}
The effect is as follows (the end and beginning will stay for 1 second):