Sphere coords, radiating from centre.

Hi, I am looking for a script or function or similar that will list all of the coordinates inside a sphere, example:

Vector3(0, 0, 0);
Vector3(1, 0, 0);
Vector3(0, 1, 0);
Vector3(0, 0, 1);
Vector3(-1, 0, 0);
Vector3(0, -1, 0);
Vector3(0, 0, -1);
Vector3(1, 1, 0);
Vector3(1, 0, 1);
Vector3(0, 1, 1);
... (skip a few)
Vector3(4, 5, -6);

as you can see all of the coords are ints
it lists every coord
it starts from the centre

I have searched google and unity answers but have only found answers about the edges of a sphere

Bonus points if you know what such a function is called
Also Bonus points if you know how to adapt it for an ellipse


So if i get the question right you want all whole number-coordinates which are inside a sphere with a given radius?

In that case, just iterate over all whole-number-coordinates of the bounding box of the sphere and do an “inside check” with the formula

x² + y² + z² < r²

You could implement it with a two method approach to keep it versatile:

// You need a "using System.Collections.Generic;" at the top
IEnumerable<Vector3> GetPointsInBoundingBox(Bounds aBounds)
	int maxX = Mathf.RoundToInt(aBounds.max.x);
	int maxY = Mathf.RoundToInt(aBounds.max.y);
	int maxZ = Mathf.RoundToInt(aBounds.max.z);
	for(int z = Mathf.RoundToInt(aBounds.min.z); z < maxZ; z++)
		for(int y = Mathf.RoundToInt(aBounds.min.y); y < maxY; y++)
			for(int x = Mathf.RoundToInt(aBounds.min.x); x < maxX; x++)
				yield return new Vector3(x,y,z);

IEnumerable<Vector3> GetPointsInSphere(Vector3 aCenter, float aRadius)
	Bounds bounds = new Bounds(aCenter, Vector3.one * aRadius*2);
	float rSquared = aRadius*aRadius;
	foreach(var p in GetPointsInBoundingBox(bounds))
		if ((p-aCenter).sqrMagnitude < rSquared)
			yield return p;

Now you can do something like this and you get a “blocky” filled sphere:

foreach(var p in GetPointsInSphere(Vector3.zero, 7))
    var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    go.transform.position = p;

If you just want the points in a List / array, just use ToList or ToArray from the System.Linq namespace:

// You need of course "using System.Linq;" at the top
Vector3[] points = GetPointsInSphere(Vector3.zero, 7).ToArray();


Keep in mind that i use Vector3 here for simplicity and compatibilty. If you really want them as int coordinates you might want to create your own “Vector3i” struct.

second edit

If you want the points to be sorted by the distance from the origin you can also use linq. just like this:

Vector3[] points = GetPointsInSphere(Vector3.zero, 7).OrderBy((v)=>v.sqrMagnitude).ToArray();