I’m trying to make a grid (in the future hopefully also other shapes) of Hexes in which all the Hexes find their neighbors by creating a Physics.OverlapSphere and adding all Gameobjects that are within a certain radius (in my case 2 as the radius of the circumcircle of the Hexes is sqrt(3). I instantiate all the Hexes inside of a Hexgrid GameObject
private void GenerateMap()
{
for (int x = 0; x < size; x++)
{
Vector3 pos = gameObject.transform.position;
if (x % 2 != 0)
pos.z -= 1.5f;
pos.x = gameObject.transform.position.x + 2.25f * x;
for (int i = (x % 2); i < size * 2; i += 2)
{
GameObject newHex = Instantiate(hexPrefab);
pos.z -= 3;
newHex.transform.position = pos;
newHex.name = x + "_" + i;
pos = newHex.transform.position;
board[x, i] = newHex;
hexes.Add(newHex.GetComponent<Hex>());
newHex.transform.parent = transform;
}
}
}
and then call a GiveNeighbors function to find all the neighbors of a Hex
private void GiveNeighbors(GameObject hexObject)
{
Collider[] colliderNeighbors = Physics.OverlapSphere(hexObject.transform.position, 2);
//hexObject.GetComponent<Hex>().makeCircle(2);
//print(colliderNeighbors.Length + " | " + hexObject.name + " | " +
hexObject.GetComponent<Collider>().transform.position);
foreach (Collider collider in colliderNeighbors)
{
if (collider.gameObject.GetComponents<Hex>() != null && collider.gameObject != hexObject)
{
hexObject.GetComponent<Hex>().neighbors.Add(collider.gameObject.GetComponent<Hex>());
}
}
}
hexPrefab:
However, Physics.OverlapSphere does return the colliders of any instantiated objects (including a Pawn object that should still be recognized) but it does return the colliders of objects that were placed on the scene before I run the game:
The List of neighbors for that Hex contains ONLY the hex that I placed there beforehand that you can see hovering slightly above.
I have no idea how or why this has been happening and after about 4 hours of scouring the internet I’ve given up and turned to here for any help.
(I know I could do this differently, but using a Physics.OverlapSphere lets me be very flexible the future shape of my map which is why I’m really trying to make it work like this)
Any help would be VERY much appreciated.