步骤

1.给表格容器添加GridLayoutGroup组件

Snipaste_2020-01-27_18-03-37.png

2.设置GridLayoutGroup组件

Snipaste_2020-01-27_18-01-31.png

3.添加元素

这里有两种加法:
一种是在Hierarchy面板里直接重复crtl+d
Snipaste_2020-01-27_18-16-09.png
另一种是用脚本动态添加,如果是确定单元个数的就用第一种,如果是动态的就用第二种。两种添加方式都会自动排列子单元。
脚本代码(挂容器上):

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

public class gameCTRLScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        createimgs(4,4);
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void createimgs(int row,int col)
    {
        for (int i = 1; i <= row; i++)
            for (int j = 1; j <= col; j++)
                createimg(i+"-"+j);
    }
    private void createimg(string name)
    {
        GameObject go = new GameObject(name);
        go.AddComponent<Image>();  //记得using UnityEngine.UI
        go.transform.SetParent(this.transform,false);
    }
}

Snipaste_2020-01-27_18-19-40.png

效果

Snipaste_2020-01-27_18-20-13.png

最后修改:2020 年 01 月 27 日
如果觉得我的文章对你有用,请随意赞赏