我想生成一个具有x体积的立方体矩阵,但我只需要表面上的立方体(我能看到的立方体)。下一段代码做它做的事情,一个完整的矩阵。我如何得到我需要的东西?
public class World : MonoBehaviour
{
public GameObject cube;
public int volume;
private void Awake()
{
for (int i = 0, x = 0; x < volume; x++)
{
for (int y = 0; y < volume; y++)
{
for (int z = 0; z < volume; z++)
{
i++;
var go = Instantiate(cube);
go.name = "Cube " + i;
go.transform.position = new Vector3
{
x = x,
y = y,
z = z
};
}
}
}
}
}
发布于 2019-02-20 03:37:50
如果只使用外部限制并忽略
// ignores the cubes that are not placed on the limits
if (x != 0 && x != volume - 1 && y != 0 && y != volume - 1 && z != 0 && z != volume - 1) continue;
i++;
var go = Instantiate(cube);
go.name = "Cube " + i;
go.transform.position = new Vector3(x, y, z);
或者如果它更容易理解
// only spawns cubes that are placed on the limits
if (x == 0 || x == volume - 1 || y == 0 || y == volume - 1 || z == 0 || z == volume - 1)
{
i++;
var go = Instantiate(cube);
go.name = "Cube " + i;
go.transform.position = new Vector3(x, y, z);
}
正如Eliasar提到的,我也建议使用一个比i
更好的变量名,比如你自己说的index
。最后,它只是一个名字,但它更简洁。但是,我也建议将它移到for
定义之外,比如
int index = 0;
for(int x = 0; ...)
而不是
for(int index = 0 , x = 0; ...)
它很难读懂
https://stackoverflow.com/questions/54773535
复制相似问题