LoginSignup
1
1

More than 1 year has passed since last update.

unityでbuttonを複数instantiateし配置する場合の注意点

Last updated at Posted at 2021-07-08

UnityでVRソフトを作る際、Buttonをスクリプトから生成していい感じに配置しようとした際にちょっとしたハマりがあったのでメモ。

やりたいこと

  • button prefabをスクリプトで複数生成
  • 等間隔にいい感じに配置

はまったこと

変な位置に設定される(参考記事のように、SetParentにworldPositionStays=falseを設定したが、謎の位置に配置される)

要因

位置設定は「SetParentの前」に行う必要があった

NGコード

setparentした後にpositionを設定すると、謎の位置に配置される(理由は不明)
```
for(int i = 0; i < mission_list.Count; i++)
{
GameObject MissionButton = Instantiate(m_menu_mission_button_prefab) as GameObject;]
MissionButton.transform.SetParent(m_canvas_menu.transform, false);

        //ミッションボタンの位置を設定。iの値により、横・縦位置を調整
        Vector3 button_width = new Vector3(m_menu_width, 0, 0) * (i % m_menu_number_of_line);
        Vector3 button_height = new Vector3(0, m_menu_height, 0) * Mathf.Floor(i / m_menu_number_of_line);
        MissionButton.transform.position = m_menu_first_position + button_width + button_height;
    }```

OKコード

setparent前に位置を設定すると、その位置情報がそのままローカル座標になってうまく配置できた
```
for(int i = 0; i < mission_list.Count; i++)
{
GameObject MissionButton = Instantiate(m_menu_mission_button_prefab) as GameObject;]

        //ミッションボタンの位置を設定。iの値により、横・縦位置を調整
        Vector3 button_width = new Vector3(m_menu_width, 0, 0) * (i % m_menu_number_of_line);
        Vector3 button_height = new Vector3(0, m_menu_height, 0) * Mathf.Floor(i / m_menu_number_of_line);
        MissionButton.transform.position = m_menu_first_position + button_width + button_height;

        MissionButton.transform.SetParent(m_canvas_menu.transform, false); 
    }```

参考記事

1
1
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
1
1