zl程序教程

您现在的位置是:首页 >  Java

当前栏目

[Unity3d基础]使用GirdLayoutGroup组件制作表格

2023-02-18 16:42:43 时间

步骤

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

2.设置GridLayoutGroup组件

3.添加元素

这里有两种加法: 一种是在Hierarchy面板里直接重复crtl+d

另一种是用脚本动态添加,如果是确定单元个数的就用第一种,如果是动态的就用第二种。两种添加方式都会自动排列子单元。 脚本代码(挂容器上):

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);
    }
}

效果