How to select adjacent cubes along edges?

I have a grid of cubes, I am using raycasting to select which ones are hit.

public void Click1(object h)
	{
		RaycastHit hit = (RaycastHit)h;
		GameObject hitGameObject = hit.collider.gameObject;
	
       Debug.Log("HIT at '" + hit.point + "' RECEIVED IN '" + gameObject.name + "'");
}

[24727-screen+shot+2014-04-04+at+1.20.58+pm.png|24727]

That works fine.

What I would like todo is select adjacent cubes to the one selected, like below:

[24728-screen+shot+2014-04-04+at+1.24.11+pm.png|24728]

And then transform them as I please.

It’s the method for selecting cubes to form the cross I am having problems with.

Currently I am using Collider[] nearObjects = Physics.OverlapSphere(hit.point, 1.75F); to get a list of objects near the hit and then iterating through the collider array, but for obvious reason it doesn’t achieve what I am after.

Any suggestions as what to try? Or any help. I have a feeling I may need a multidimensional array, but been new to c# I may be very wrong.

The better way to solve this problem is to put a reference to all of your cubes in a 2D array. Then when the user clicks, you can go to your array and get all the cubes in the specified row and specified column. If you really want to do it dynamically, you can use Physics.RaycastAll() and do a raycast in the four directions.

An in-between solutions would be to get an array of all the cubes. You could do it by putting the same tag on all the cubes and use GameObject.FindGameObjectsWithTag(). Then you could simply compare both the x and y position of the clicked cubed against the x and y positions of all the entries in the array. You will need some sort of tolerance (i.e. don’t compare floats directly). All the cubes with close ‘y’ positions and all the cubes with close ‘x’ positions will be the ones you want.

I am doing this exact thing in a game I released recently.
Basically what I do is when the first tile gets hit by the mouse raycast, the tile sends raycasts in all four directions, which then triggers whatever I need to do with them, and then a new raycast, until there is nothing more to hit. Essentially I just make a chain reaction :slight_smile: