I am trying to make a script that will take 2 objects and determine if any vertices have the same x and z coordinates, if they do this should make the first objects vertex y coordinate = the second objects vertex y coordinate, however I am running too many loop and cannot get this to work properly, I need help simplifying it or finding errors. it just makes unity crash at the moment.
public static void StitchCells(GameObject cell)
{
InitialCellScan();
Vector2 up = new Vector2((cell.transform.position.x / cellSize) + 1, (cell.transform.position.z / cellSize));
Vector2 down = new Vector2((cell.transform.position.x / cellSize) - 1, (cell.transform.position.z / cellSize));
Vector2 right = new Vector2((cell.transform.position.x / cellSize), (cell.transform.position.z / cellSize) + 1);
Vector2 left = new Vector2((cell.transform.position.x / cellSize), (cell.transform.position.z / cellSize) - 1);
Vector2[] nextCellPosition = new Vector2[4];
nextCellPosition[0] = up;
nextCellPosition[1] = down;
nextCellPosition[2] = right;
nextCellPosition[3] = left;
foreach (Vector2 nextposition in nextCellPosition) {
if (existingCells.Contains(nextposition))
{
GameObject[] scannedCells = GameObject.FindGameObjectsWithTag(cellTag);
foreach (GameObject nextCellObject in scannedCells)
{
if (Mathf.RoundToInt(nextCellObject.transform.position.x / cellSize) == nextposition.x)
{
if (Mathf.RoundToInt(nextCellObject.transform.position.z / cellSize) == nextposition.y)
{
Mesh thisCellsMesh = cell.GetComponent<MeshFilter>().mesh;
Vector3[] theseVertices = thisCellsMesh.vertices;
Mesh nextCellsMesh = nextCellObject.GetComponent<MeshFilter>().mesh;
Vector3[] nextVertices = nextCellsMesh.vertices;
for (int thisVert = 0; thisVert < theseVertices.Length; thisVert++)
{
Vector3 thisPoint = cell.transform.TransformPoint(theseVertices[thisVert]);
for (int nextVert = 0; nextVert < nextVertices.Length; nextVert++)
{
Vector3 nextPoint = cell.transform.TransformPoint(nextVertices[nextVert]);
if (thisPoint.x == nextPoint.x && thisPoint.z == nextPoint.z)
{
thisPoint.y = nextPoint.y;
theseVertices[thisVert] = cell.transform.InverseTransformPoint(thisPoint);
}
}
}
thisCellsMesh.vertices = theseVertices;
thisCellsMesh.RecalculateBounds();
thisCellsMesh.RecalculateNormals();
}
}
}
}
}
}