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秒):文章来源:https://www.toymoban.com/news/detail-724531.html
文章来源地址https://www.toymoban.com/news/detail-724531.html
到了这里,关于Unity ScrollView循环滚动播放(有详细注释)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!