0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】LoopScrollRect をスナップさせる試み

Posted at

概要

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?