スクロールでメニューボタンを表示する

備忘録
スクロールでボタンを表示したい場合、
UIよりScroll Viewを使う

スクロールでメニュー

Scroll ViewははじめCanvasの直下に配置していたけど、謎の無限ループ地獄に入り、Panelを作成しその下に配置。これで納まる。
ScrollRectというものをアタッチするけど、それがCanvasに付けてしまうと何か具合が悪かったよう
ななおでPanelにScrollRectをアタッチ。
Content,Viewport、HorizontalScrollber、VerticalScrollbarの欄にそれぞれ同名のオブジェクトをアタッチ

表示するボタンはPrefab化。

今回はメニューをMenuManagerでまとめるので同名のオブジェクトを作成
そこにMenuManagerとユーザーデータをアタッチ
MenuManagerの階層が重要でPanelの子オブジェクトとして置く。
同階層にすると参照できないよう・・・
MenuManagerのButtonPrefab欄にPrefab化したボタンをアタッチ。
ScrollRectという変数の欄は何もアタッチしない。
これは変数を初期化した関係でここに表示されるよう・・

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class MenuManager : MonoBehaviour
{
    private UserdataManager userdataManager;
    private Player player;
    public Button buttonPrefab;
    public ScrollRect scrollRect;

    void Start()
    {
        scrollRect = GetComponentInParent<ScrollRect>();
        userdataManager = GetComponent<UserdataManager>();
        player = userdataManager.GetUserData();
       
        SetMenu();
    }

    public void SetMenu()
    {
        // Scroll ViewのContentを取得
       
        Transform content = scrollRect.content;


        // ボタンの生成や制御の処理を追加 player.pointDataArray.Length;
        for (int i = 0; i < player.pointDataArray.Length; i++)
        {
            // Buttonをインスタンス化してContentの子として追加
            Button newButton = Instantiate(buttonPrefab, content);

            // ボタンのプロパティや位置を設定
            newButton.transform.localPosition = new Vector3(0, -i * 30, 0); // Content内の位置を設定


            TextMeshProUGUI textComponent = newButton.GetComponentInChildren<TextMeshProUGUI>();

            textComponent.text = "Button " + i;s
        }

        // ボタンの生成が完了したので、レイアウトの再計算を行う
        LayoutRebuilder.ForceRebuildLayoutImmediate(content.GetComponent<RectTransform>());
    
    }
}

ずー-っとエラーが出続けた理由がTextで構文を作っていたけど、TMPだったせい。
何で私のunityはTextがないんだろうか・・Windowsだから??謎。

取り敢えず表示は出来たけど、ボタンの大きさの変更と表示の有無など調整は来週かな。

この記事が参加している募集

この記事が気に入ったらサポートをしてみませんか?