Unity 3D: 在 (0, 0, 0) 坐标四周生成 10x10 网格
以下是一种实现方法:
-
创建一个空的 GameObject,并将其命名为'Grid'。
-
编写一个脚本,用来在 Grid 周围生成 GameObjects。脚本中需要包含以下内容:
a. 一个公共变量,用来设置生成的 GameObject 的数量。在本例中,将其设置为 100 (10*10)。
b. 一个公共变量,用来设置生成的 GameObject 之间的间距。在本例中,将其设置为 1。
c. 一个公共变量,用来设置生成的 GameObject 的 Prefab。在本例中,将其设置为一个 Cube。
d. 一个 Start() 函数,在其中进行 GameObject 的生成。可以使用一个嵌套循环,分别在 x、y、z 轴上生成一系列的 GameObject。
e. 一个 Update() 函数,在其中检测用户输入。如果用户按下了某个键,可以将生成的 GameObject 进行销毁。
-
将脚本挂载到 Grid 上,运行游戏即可看到生成的 GameObjects。
下面是示例代码:
public class GridGenerator : MonoBehaviour
{
public int numObjects = 100;
public float spacing = 1.0f;
public GameObject prefab;
void Start()
{
int numPerRow = Mathf.CeilToInt(Mathf.Sqrt(numObjects));
float offset = (numPerRow - 1) * spacing / 2.0f;
for (int x = 0; x < numPerRow; x++)
{
for (int y = 0; y < numPerRow; y++)
{
for (int z = 0; z < numPerRow; z++)
{
if (x * numPerRow * numPerRow + y * numPerRow + z < numObjects)
{
GameObject obj = Instantiate(prefab, new Vector3(x * spacing - offset, y * spacing - offset, z * spacing - offset), Quaternion.identity);
obj.transform.parent = transform;
}
}
}
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
}
}
}
原文地址: https://www.cveoy.top/t/topic/oeey 著作权归作者所有。请勿转载和采集!