AddComponent conforms to shape, size, position of mesh. How do I do this manually?

I have a small marching cubes set that changes size shape and position on runtime, relative to its objects relative space. When I delete the objects spherecollider then add a new spherecollider the local center position and radius conform to the mesh generated by marching cubes. The problem is destroying the spherecollider then adding a new one just to change the size and position of the sphere is pretty inefficient IMO.

What is a good way to set the SphereCollider’s position and size the same way it is set automatically?

The problem you just have discovered is called the “minimal bounding sphere”. Unfortunately there’s no easy reliable way to obtain / calculate that sphere. See Algorithms for some implementations. In most cases it’s enough to calculate an approximate solution since an exact solution can be very CPU intensive and it gets worst the most points you have.

edit

Just found this old question with was about the very same thing.

So I whipped something up based on your response “Bunny83”. It’s an approximation I suppose, since it doesn’t take into account all the vertices in the mesh. Also while comparing distance from center it uses only what has been checked. But alas “Most of the time is good enough.”

Vector3 Center=Vector3.zero;
float Furthest=0;
int numberchecked=0;
for(int tt=0; tt<vc; tt+=7)
{
	numberchecked++;
	Center+=vertices
;
    				
    	float dd=((Center/numberchecked)-vertices[tt]).magnitude;
    	if(dd>Furthest)
    	{
    		Furthest=dd;
    	}
    }
    
    coll.radius=Furthest-.13f;
    coll.center=(Center/numberchecked);