1. 生成位置在同一平面内,n*n方块组成的格子
注:使用时需将Prefab拖入下图所示位置使用
Grid Size为n的大小
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GridMaker : MonoBehaviour
{
public int GridSize = 4;
public GameObject SingleGrid;
//public GameObject NumberText;
// Start is called before the first frame update
void Start()
{
GenerateGrids(GridSize);
}
public void GenerateGrids(int gridSize)
{
//存储只是为了后续代码,可忽略
GameObject[] Grids = new GameObject[GridSize * GridSize];
int[] GridNumbers = GenerateRandomIntSet(GridSize * GridSize);
for (int i = 0; i < GridSize * GridSize; i++)
{
Debug.Log(GridNumbers[i]);
}
for (int x = 0; x < GridSize; x++)
{
for (int y = 0; y < GridSize; y++)
{
Grids[x * y] = Instantiate(SingleGrid, new Vector3(x, y, 0), Quaternion.identity);
//Text SingleNumber = Grids[x * y].AddComponent<Text>();
//var canvas = FindObjectOfType<Canvas>();
//Grids[x * y].transform.SetParent(canvas.transform);
//SingleNumber.text = GridNumbers[x * y].ToString();
}
}
}
// Update is called once per frame
void Update()
{
}
}
2. 生成围绕一点旋转的n*n方块
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GridMaker3D : MonoBehaviour
{
public int GridSize = 4;
public GameObject SingleGrid;
public int DegreeTotal = 360;
private Vector3 centerPos = new Vector3(0, 0, 0); //可设置为用户初始位置
private float radius = 4; //物理离 centerPos的距离
//public GameObject NumberText;
// Start is called before the first frame update
void Start()
{
GenerateGrids(GridSize);
}
public void GenerateGrids(int gridSize)
{
GameObject[] Grids = new GameObject[gridSize * gridSize];
int[] GridNumbers = GenerateRandomIntSet(gridSize * gridSize);
for (int i = 0; i < gridSize * gridSize; i++)
{
Debug.Log(GridNumbers[i]);
}
centerPos = transform.position;
centerPos = transform.position;
//每SingleAngle度生成一个圆
int singleAngle = 360 / gridSize;
for (int y = 0; y < gridSize; y++)
{
for (int x = 0, angle = 0; angle < 360; angle += singleAngle, x++)
{
//先解决你物体的位置的问题
// x = 原点x + 半径 * 邻边除以斜边的比例, 邻边除以斜边的比例 = cos(弧度) , 弧度 = 角度 *3.14f / 180f;
float xPos = centerPos.x + radius * Mathf.Cos(angle * 3.14f / 180f);
float zPos = centerPos.z + radius * Mathf.Sin(angle * 3.14f / 180f);
Grids[x * y] = Instantiate(SingleGrid, transform);
//GameObject obj1 = GameObject.CreatePrimitive(PrimitiveType.Cube);
//设置物体的位置Vector3三个参数分别代表x,y,z的坐标数
//obj1.transform.position = new Vector3(xPos, 2, zPos);
Grids[x * y].transform.position = new Vector3(xPos, y, zPos);
Grids[x * y].transform.localEulerAngles = new Vector3(0, -angle);
}
}
}
// Update is called once per frame
void Update()
{
}
}
附:如何将Unity基础GameObject设置为Prefab:
拖下去就好了:)