Getting list of gamobjects close to the one clicked on

I have a huge group of balls all next to eachother some touching some not. I want to test if there are balls of the same color within a certain distance like half the width of a ball.
How would i do that?

if (ballpicked == “Any other balls within a half a ball width”) {

}

public class Ball : MonoBehaviour {

public Color[ ] colors;
private Color ballpicked;

// Use this for initialization
void Start () {
GetComponent().material.color = colors[Random.Range (0, 4)];
}

// Update is called once per frame
void Update () {

}
void OnMouseDown(){
if (Input.GetKey(“mouse 0”)){

ballpicked = GetComponent ().material.color;

if (ballpicked == “Any other balls within a half a ball width”) {

}

Destroy (gameObject);
}
}
}

Unity - Scripting API: Physics.OverlapSphere , you might need to do some additional checking depending on the exact logic, but this will get any colliders that are within the given distance

Yeah i get the collision thing. But these balls don’t necessarily touch or collide but are right next to each other. They could be almost touching and still need to detect if they are with in a half a balls radius.

do i need to add all the balls to an array and loop through that arrays position?
I thought there maybe an easier way?

public class SpawnBalls : MonoBehaviour {
    public Rigidbody ball;
    public float waittime = 0.5f;

    // Use this for initialization
    void Start () {
        spawn ();
    }
   
    // Update is called once per frame
    void Update () {
        //Instantiate (ball);

    }
    public void spawn(){
        //yield WaitForSeconds(waittime);

            for (var i = 0; i < 10; i++) {
                Instantiate (ball);
            }
    }

}

when the documents say “touching or within the sphere” they mean the sphere you specify in the function, not the collider attached to the gameobject you’re casting from.

So say the spheres you are using are all 1 unit in size. You can cast and “overlapsphere” of radius 2 (or whatever) and detect all the colliders within 2 units of the center of the one you are casting from.

1 Like

I think I’m close now thanks!!