How to delete an object if there is another object of the same type at that position ?
Hi,I am doing a simple randomGeneration,my generation code works fine but it has a tendency to spawn more than 1 tile at a give position so i have made the script below to delete the gameobejects if another one of their kind is at their position,but it doesn't work it deletes non overlapping objects aswell.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DestroyOnTouch : MonoBehaviour {
public List<GameObject> walls = new List<GameObject>();
public List<GameObject> tiles = new List<GameObject>();
void Start ()
{
Invoke ("Destroy",2f);
}
void Destroy()
{
walls.AddRange(GameObject.FindGameObjectsWithTag("Walls"));
tiles.AddRange(GameObject.FindGameObjectsWithTag("Tile"));
StartCoroutine(DestroyWalls());
StartCoroutine(DestroyTiles());
}
IEnumerator DestroyWalls ()
{
yield return null;
for(int c = 0; c < walls.Count; c++)
{
for(int y = 0; y < walls.Count; y++)
{
if(c > y || y > c)
{
//yield return new WaitForSeconds(0.1f);
if(walls[c].transform.position == walls[y].transform.position)
{
Destroy(walls[y],0.1f);
walls.Remove(walls[y]);
}
}
}
}
}
IEnumerator DestroyTiles ()
{
yield return null;
for(int c = 0; c < walls.Count; c++)
{
for(int y = 0; y < tiles.Count; y++)
{
if(c > y || y > c)
{
//yield return new WaitForSeconds(0.1f);
if(tiles[c].transform.position == tiles[y].transform.position)
{
Destroy(tiles[y],0.1f);
walls.Remove(tiles[y]);
}
}
}
}
}
}
Answer by hexagonius · Sep 13, 2015 at 03:29 PM
Eliminating the problem where it comes from is probably the better idea. For the random generator:
Create a List of as many positions as you need, or all from which you want to pick (like a triple for loop for x, y and z). use your generator to pick a random position from the list of unique positions and delete the ones you picked already.
That is indeed true but i am not an experienced coder how would u go about generating a 2d dungeon ? i dont need code i just need some pointers.
That more of a discussion than a question really. And different from this topic as well, please ask it separately. If my answer satisfied your case here, please mark it as answered.
Your answer
Follow this Question
Related Questions
Getting objects out of a list and then comparing them 0 Answers
All GameObjects list to a GameObject? 0 Answers
How To Find GameObject From List And Add To Player List 0 Answers
What range of values need to be inserted if we need to pull a random item from the list? 0 Answers
Edit properties of certain list items,Changing properties of objects in a list (c#) 1 Answer