Unity/リスト表示/使いまわし
提供: 初心者エンジニアの簡易メモ
目次
LoopScrollRectとは
無料で使える、使い回しができるリスト
インストール
- Unityメインメニュー/Window/PackageManager/左上の+/gitURLから以下を追加
- https://github.com/qiankanglai/LoopScrollRect.git
- Packages/LoopScrollRectが追加されてることを確認
サンプル追加
- Unityメインメニュー/Window/PackageManager/左上の+/gitURLから以下を追加
- https://github.com/qiankanglai/LoopScrollRect.git
- SamplesをimportするとAssets/Samples/LoopScrollRect/1.1.2-p1以下にDemoが追加される
縦リスト作成
- Unityメインメニュー/GameObject/UI/LoopVerticalScrollRect
- Assets/Canvas/LoopVerticalScrollRectが作成されることを確認
- LoopVerticalScrollRectのInspectorで、AddComponentから、VerticalLayoutGroupを追加し、ControlChildSizeのWIdthとHeightにチェックと、ChildForceExpandのWidthにチェック。
- ProjectのAssetsの下にPrefabsのdirを作成しておく。
- LoopVerticalScrollRect/Contentの下に、適当にImageやTextなどのコンテンツを作り、AddComponentから、LayoutElementを追加して、MinHeightにチェックを入れ縦幅(例えば200とか)を入れ、FlexibleWidthにチェックを入れ1を入れ、Prefabsの下にドラッグ。
- MainCameraとかに、以下LoopScrollRectMain.csを追加し、InspectorのscrollRectに、LoopVerticalScrollRectオブジェクトをドラッグ
LoopScrollRectMain.cs
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoopScrollRectMain : MonoBehaviour, LoopScrollPrefabSource, LoopScrollDataSource
{
[SerializeField] LoopVerticalScrollRect scrollRect;
[SerializeField] GameObject prefab;
[SerializeField] int totalCount = 10;
Stack<Transform> pool = new Stack<Transform>();
void Start()
{
scrollRect.prefabSource = (LoopScrollPrefabSource)this;
scrollRect.dataSource = (LoopScrollDataSource)this;
scrollRect.totalCount = totalCount;
scrollRect.RefillCells();
// スクロールバーの縦幅調整
scrollRect.verticalScrollbar.transform.GetComponent<RectTransform>().sizeDelta
= new Vector3(30f, scrollRect.content.sizeDelta.y);
}
// Objectが枠中になった時
GameObject LoopScrollPrefabSource.GetObject(int index)
{
if (pool.Count == 0)
{
return Instantiate(prefab);
}
Transform candidate = pool.Pop();
candidate.gameObject.SetActive(true);
return candidate.gameObject;
}
// Objectが枠外になった時
void LoopScrollPrefabSource.ReturnObject(Transform trans)
{
trans.gameObject.SetActive(false);
trans.SetParent(scrollRect.transform, false);
pool.Push(trans);
}
// 要素が表示される時
void LoopScrollDataSource.ProvideData(Transform trans, int index)
{
trans.Find("Text").GetComponent<Text>().text = "文章" + index.ToString();
}
}
縦リストにスクロール追加
- LoopVertialScrollRectの下にUI/Scrollbarを追加。
- ScrollbarのInspectorのScrollbarのDirection をTopToBottomに変更
- LoopVertialScrollRectのInspectorのVerticalScrollbarに、上で作ったScrollbarをドラッグ。
スクロールバーが動かないとき
Canvasを作ったときに自動で作られる、EventSystemが、ヒエラルキーに作成されてるか確認して、なければ追加する。
スクロールバーの操作バーの縦幅がおかしくなるとき
Prefabsに入れたPrefabのオブジェクトのInspectorを開いて、LayoutElementなどが正しく設定されてるか確認。MinHeightに縦幅(例えば200とか)を、入れて、FlexibleWidthに、チェックをいれ、1を入れる。
コンテンツが左によるとき
ipadとかで、横幅になる際に、左によってしまう場合
- LoopVerticalScrollRect/ContentのInspectorのRectTransformをLeftからCenterへ
参考
https://github.com/qiankanglai/LoopScrollRect/blob/master/Samples~/Demo/Scripts/InitOnStart.cs
https://light11.hatenadiary.com/entry/2022/05/16/201949
その他
TableScrollViewという別のプラグインもあり
