Unity ScrollView循环滚动播放(有详细注释)

Unity3D ScrollView循环滚动播放

首先创建一个ScrollView在UI上
在这里插入图片描述
在Content上挂载脚本,将ScrollView赋值给Parent。
在这里插入图片描述
当Content的高度大于ScrollView的容量高度时便开始滚动。
以下是脚本代码:

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;
    }
}


效果如下(结尾和开头会停留1秒):

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44099953/article/details/131676263