My objective here is to have each generated 2d object [Block] detect whether there is an object above, below, or to the right or left.
What would be the best way to do this?
My objective here is to have each generated 2d object [Block] detect whether there is an object above, below, or to the right or left.
What would be the best way to do this?
you could do that by giving every block a collider and then using the Physics2D.CircleCast() function, which returns a list of collides within the circle you cast. But I’m guessing you’re positioning your blocks in a strict grid. In that case the best solution would be to store all the blocks in a two dimensional array based on their x and y position. This way you can easily check surrounding blocks by entering the blocks position plus/minus 1.
Gameobject[,] blocks;
public GameObject blockPrefab;
public Vector2Int start;
public Vector2Int end;
void Start()
{
blocks = new GameObject[Mathf.Abs(start.x)+Mathf.Abs(end.x),Mathf.Abs(start.y)+Mathf.Abs(end.y)];
for(int x= start.x ; x < end.x ; x++)
{
for(int y= start.y ; y < end.y ; y++)
{
GameObject go = Instantiate(blockPrefab,new Vector2 (x,y),Quaternion.Euler(0,0,0));
blocks[x-start.x,y-start.y] = go;
}
}
}