I mean automatic to find the outer grid square :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateGrid : MonoBehaviour
{
public GameObject gridPrefab;
public int gridWidth = 10;
public int gridHeight = 10;
public int gap;
public float spawnSpeed = 0;
public bool gridGenerated = false;
void Start()
{
StartCoroutine(CreateGrid());
}
IEnumerator CreateGrid()
{
for (int x = 0; x < gridWidth; x++)
{
yield return new WaitForSeconds(spawnSpeed);
for (int z = 0; z < gridHeight; z++)
{
yield return new WaitForSeconds(spawnSpeed);
GameObject block = Instantiate(gridPrefab, Vector3.zero, gridPrefab.transform.rotation) as GameObject;
block.transform.parent = transform;
block.transform.localPosition = new Vector3(x + x * gap, 0, z + z * gap);
block.tag = "Grid Block";
}
}
gridGenerated = true;
}
}
I marked them selected them in the screenshot to show what I mean by the outer square. I want to find automatic by some code logic only the outer square of the grid no matter what is the grid size if it's 10 on 10 or 3 on 7
This is working but with two problems that prevent from it to be automatic :
In another script I'm getting all the grid blocks positions :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetGridPos : MonoBehaviour
{
public GenerateGrid generateGrid;
private List<Vector3> gridBlocksPositions = new List<Vector3>();
private List<Vector3> gridOuterBlocks = new List<Vector3>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (generateGrid.gridGenerated)
{
var blocks = GameObject.FindGameObjectsWithTag("Grid Block");
foreach (GameObject pos in blocks)
{
gridBlocksPositions.Add(pos.transform.position);
if (pos.transform.position.x == 0 && pos.transform.position.y == 0
|| pos.transform.position.z == 18 || pos.transform.position.x == 18
|| pos.transform.position.y == 0 && pos.transform.position.z == 0)
{
gridOuterBlocks.Add(pos.transform.position);
}
}
generateGrid.gridGenerated = false;
}
}
}
The problems :
In this case I know the grid is 10 x 10 so there are 100 blocks and the gap between each blocks is 1 so the 4 sides length of the outer grid square will be 18 in this case but I want to find it automatic not to type the length on my own.
I need to add to the calculation also the gap factor.
So I'm still missing the right formula to get the grid outer blocks positions.