这里有两种加法: 一种是在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);
}
}