Greetings!
I want to instantiate a Gameobject on a certain position, but before doing so, I need to know if this position is empty. What’s the best way to do it?
Some suggested using FindGameObjectsWithTag, but it should detect any GameObject, not just a given tag.
Thanks!
When you create your gameobjects, I suggest you add them to a 2D grid of objects like so:
public Vector2 Mapsize; // Assign in inspector
private GameObject[,] objects;
public void Start()
{
objects = new GameObject[(int)Mapsize.x, (int)Mapsize.y];
}
public void CreateObject(GameObject gameObj, int x, int y)
{
// Not make object if there is already one on this coordinate or outside of the bounds of the map
if (!InRange(x,y) || ContainsObject(x,y)) return;
var obj = Instantiate(gameObj, new Vector3(x, y, 0), Quaternion.identity) as GameObject;
objects[x,y] = obj;
}
public bool ContainsObject(int x, int y)
{
return objects[x,y] != null;
}
private bool InRange(int x, int y)
{
return (x >= 0 && y >= 0 && x <= objects.GetUpperBound(0) && y <= objects.GetUpperBound(1));
}