Detecting nearest point of colission in a sphere

Alright so here is my problem. I have a game where I need an object to snap to the nearest point among a series of objects. As far as I can figure, I need to have the object send out something similar to raycasts in a sphere around my object doing the detecting and then compare the points to find the closest point. I already know how to move it to that point and how to use raycasts but im not sure how to detect it in a sphere instead of just a line. Any help would be greatly appreciated. Also I am programming in javascript

Look into functions like this one: http://unity3d.com/support/documentation/ScriptReference/Physics.SphereCastAll.html

You could start using Physics.OverlapSphere, which will return an array with all colliders inside or touching the spherical volume specified. OverlapSphere actually checks only the bounds (a box aligned to the axis and completely enclosing the collider) so you will have to refine the results using raycast or Physics.SphereCast - SphereCast is a kind of “fat” Raycast: it projects an imaginary sphere in the direction specified, and returns true if something is hit - and a RaycastHit structure with info about the hit point, normal, etc.

You can use a small radius in OverlapSphere initially; if nothing is hit, double the radius and try again. When one or more colliders are returned by OverlapSphere, do a SphereCast with a suitable radius (sufficient to enclose the object) directed to each of them, and select the closest one.

The function below does this: it tries to find the object that’s closer to myObj, and fills the public RaycastHit var nearestHit with the hit info of the nearest object. Place this code in your script and call this function when you want to find the nearest object to myObj.

It wasn’t tested, thus let me know if something goes wrong.

var nearestHit: RaycastHit;

function FindNearestObj(myObj: Transform){
    var targets: Colliders[];
    var qTargets = 0;
    var radius: int;
    for (radius = 2; qTargets == 0; radius *= 2){
        targets = Physics.OverlapSphere(myObj.position, radius);
        qTargets = targets.length;
    }
    var rObj = myObj.collider.bounds.extents; // estimate object radius
    var hit: RaycastHit;
    var minDist = Mathf.Infinity;
    for (col: Collider in targets){
        var dir = col.transform.position - myObj.position;
        if (Physics.SphereCast(myObj.position, rObj, dir, hit){
            if (hit.distance < minDist){
                nearestHit = hit;
                minDist = hit.distance;
            }
        }
    }
}

Ok well I finaly got it working using ClosestPointOnBounds. Had a lot of trouble because my modeler messed up on making the model. Thanks for everyone’s suggestions.