具有动态单元的Unity网格布局组

时间:2020-09-16 13:43:12

标签: c# android unity3d

我正在为我的应用程序在一家商店工作,并且尝试对项目使用“网格布局”组。我的问题是网格中的单元不会动态更改其大小,因此它是固定大小。如何使它们具有动态性?

这是现在的样子: enter image description here

,这是将分辨率更改为例如2560x1440时的外观: enter image description here

如您所见,单元格保持相同大小,并且看起来不是很好。我希望更改单元格的大小,以便它可以更多地填充空间,但仍保持2行。

这里有更多详细信息:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要使用脚本手动更改它,有2种方法。

  1. 更改单元格的内部尺寸和间距
  2. 更改本地规模。

数字1的示例

    Vector2 baseSize = new Vector2(800,600); // Base size of the screen
    Vector2 baseCellSize; // In editor Cell Size for GridLayoutComponent
    Vector2 baseCellSpacing; // In editor Cell Spacing for GridLayoutComponent
    GridLayoutGroup layoutGroup; //Component
    void Start()
    {
        layoutGroup = GetComponent<GridLayoutGroup>();
        baseCellSize = layoutGroup.cellSize;
        baseCellSpacing = layoutGroup.spacing;
    }
    
    void Update()
    {
        Vector2 screenSize = new Vector2(Screen.width, Screen.height); // Current screen size
        layoutGroup.cellSize = (screenSize / baseSize) * baseCellSize;
        layoutGroup.spacing = (screenSize / baseSize) * baseCellSpacing;
    }

请注意,这不能保持正确的缩放比例,并且项目可能会被拉伸。为此,您需要致力于在宽度或高度上缩放。然后,您将像这样创建screenSize变量 Vector2 screenSize = new Vector2(Screen.width, Screen.width);请注意两个字段中的Screen.width

编辑:您还可能希望将两个轴的内容大小调整器设置为不受限制