Find all gameobjects with z position and delete

Hey there!

For a game I am currently working on I have made a little tile system. Now at some point in the game, the player will be able to delete an entire row of GameObjects. Each of those GameObjects have the z position in common. So my question is, how can I find all ingame GameObjects with a z position of for example 0 and tag “Tile”? I have searched and tried to figure it out, but I can’t seem to find an easy and smart solution.

Thank you so much for your help!

I guess you need something like this:

GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");

foreach (GameObject tile in tiles)
     if(tile.transform.position.z == 0.0f)Destroy(tile);

Hope this helps you on your way :wink:

Consider using a data structure that represents your tile-based game. For example you could use a List of List:

// C#
using System.Collections.Generic;

List< List<GameObject> > tiles;

Then when you need to remove a particular row of tiles, you just get the correct sub-list and iterate through it:

List<GameObject> row = tiles[index];
foreach(GameObject tile in rows)

Then you can decide whether removing the row completely from the data or just emptying the list 'depending on your needs):

// Removing:
tiles[index] = null;
// Emptying: