I have several game objects in my scene that are obstacles, and because they are procedurally generated I want to check in case two of them have the same position.
PD: sorry for my english.
I have several game objects in my scene that are obstacles, and because they are procedurally generated I want to check in case two of them have the same position.
PD: sorry for my english.
You can assing a tag and with using this tag you can call all objects that holds the same tag into a gameObjects list: List<GameObject> _list = GameObject.FindAllGameObjectsWithTag(YOURTAG)
and after that you can check if there are objects that holds same position like:
for(int i = 0;i<_list.length;i++)
{
for(int p = 0;p<_list.length;p++)
{
if(i != p)
{
if(_list*.transform.position == _list[p].transform.position)*
{
Debug.Log(“Same Position!”);
}
}
}
}
If you want to spawn an object(OBSTACLE) that holds different position from all others before it you can write a bool function which returns true-false if there is a objects that have same position so you can spin random once again to find different position as:
bool checkSame(List _list)
{
for(int i = 0;i<_list.length;i++)
{
for(int p = 0;p<_list.length;p++)
{
if(i != p)
{
if(_list*.transform.position == list[p].transform.position)
_{*
return true;
}
}
}
}
return false;
}
This function will return if there are two objects that have same position.
One way of doing this is to have whatever script is managing these instantiations to keep a list of references of these objects. I don’t know if these objects are being generated all at once at startup or continually through the game but, in any case, before creating one object you check the list of current objects and see if the intended position for the new object is already occupied by someone on the list. If not, instantiate the object and add it to the list.
To check for intersection you could use transform.position simply (if the magnitude of pos1 - pos2 is smaller than some threshold return true) but that doesn’t guarantee there won’t be intersection if you have objects with largely different shapes and sizes. The ideal solution depends on what you’re doing, really. Maybe intersection is not a problem. If it is, I’d probably use physics collision system, with some function like physics.spherecast or cube or capsule etc. Or maybe you are instantiating things on a grid, then instead of physics, or transform.position I’d use simply the grid coordinates.
I hope any of this helps.