Hey guys! I’m looking for a simple (or less simple) algorithm, that will create a sphere made of cubes with some adjustable radius. Something like this for cube, but for sphere.

var prefab : Transform;
var oneSide : int = 5;
function Start(){
var x : int = 0;
var y : int = 0;
var z : int = 0;
while(x <= oneSide){
while(y <= oneSide){
while(z <= oneSide){
Instantiate(prefab, transform.position + Vector3(x,y,z), transform.rotation);
z++; }
y++;
z = 0;}
x++;
y = 0;
z = 0;}}

And I don’t wan’t to rotate the cubes to the center.

– David

I haven’t tried this, but this blog post seems to describe exactly what you want.

The code you have will work, you just need to check to see if transform.position + Vector3(x,y,z) is *in* the target sphere, an only instantiate if it is.

While I’m thinking of a better (more efficient) option, why not find the (cubic) bounds of the sphere you want to convert, flood it with cubes of the resolution you want, then run a quick collision check to see which of the cubes are held within the sphere?

It seems like this would work but, again, I can’t imagine it’s the **best** way to go about it.

This solution worked for me. As said above you can make a cubical grid and check distance from a center point. This code makes a sphere of cubes that looks like something from MineCraft, but the idea is the same, just delete all the components from the brick and you have a grid of transforms. If you just want the shell of the sphere add a minimum distance in the distance check. You might want to reduce the number of bricks though. I’m running this on a 1060 GPU and I’m only getting a few frames.

```
public GameObject brick;
public int gridWidth;
public int gridDepth;
public int gridHeight;
public List<GameObject> gridElements;
public GameObject gridCenter;
public Bounds gridBounds;
void Start()
{
gridWidth = 240;
gridDepth = 240;
gridHeight = 240;
gridCenter = new GameObject();
brick = GameObject.CreatePrimitive(PrimitiveType.Cube);
brick.transform.localScale = new Vector3(6, 6, 6);
for (int y = 0; y < gridHeight; y = y + 6)
{
for (int z = 0; z < gridDepth; z = z + 6)
{
for (int x = 0; x < gridWidth; x = x + 6)
{
var gridElement = Instantiate(brick, new Vector3(x, y, z), Quaternion.identity);
gridElements.Add(gridElement);
gridBounds.Encapsulate(gridElement.transform.position);
}
}
}
Destroy(brick);
gridCenter.transform.position = gridBounds.center;
foreach(GameObject gridElement in gridElements)
{
var distance = Vector3.Distance(gridElement.transform.position, gridCenter.transform.position);
if (distance > 120)
Destroy(gridElement);
else
gridElement.transform.parent = gridCenter.transform;
}
gridCenter.transform.position = new Vector3(0, 0, 0);
}
```