概要
LoopScrollRect にスナップ機能が無かったので、拡張メソッドを作ってみました。
注意点
Padding や Spacing を利用すると正しく機能しなくなります。
Cell 内に余白を設ければ一応 Spacing のような事ができます。
実装メモから記事化まで半年以上経っていたので、不具合があったり正式にスナップ機能が実装されていたりするかもしれません。コメントをいただけると助かります。
コード
お手持ちの LoopScrollRectEx に追加してご利用ください。
using UnityEngine;
using UnityEngine.UI;
public static class LoopScrollRectEx
{
public static void Snap(this LoopScrollRectBase scrollRect, float width, int defaultViewCount = int.MaxValue, float duration = 0.2f)
{
scrollRect.StopMovement();
if (scrollRect.content.childCount <= defaultViewCount) return;
var firstIndex = scrollRect.GetFirstItem(out var offset);
scrollRect.SrollToCellWithinTime(firstIndex + (offset >= -width * 0.5f ? 1 : 0), duration);
}
public static void SnapX(this LoopScrollRectBase scrollRect, GameObject cell, int defaultViewCount = int.MaxValue, float duration = 0.2f)
{
scrollRect.StopMovement();
if (scrollRect.content.childCount <= defaultViewCount) return;
var firstIndex = scrollRect.GetFirstItem(out var offset);
var width = (cell.transform as RectTransform).rect.size.x;
scrollRect.SrollToCellWithinTime(firstIndex + (offset >= -width * 0.5f ? 1 : 0), duration);
}
public static void SnapY(this LoopScrollRectBase scrollRect, GameObject cell, int defaultViewCount = int.MaxValue, float duration = 0.2f)
{
scrollRect.StopMovement();
if (scrollRect.content.childCount <= defaultViewCount) return;
var firstIndex = scrollRect.GetFirstItem(out var offset);
var width = (cell.transform as RectTransform).rect.size.y;
scrollRect.SrollToCellWithinTime(firstIndex + (offset >= -width * 0.5f ? 1 : 0), duration);
}
}