- Home /
Protection against intersection of generated objects.
On the scene during the game, game objects are generating randomly.
We need to make sure that the created objects do not intersect (that is, do not overlap each other).
At the moment I'm using this:
// Repeat until there is a free space or until the number of attempts is more than 10
for (int attempt = 0; attempt <10; attempt ++)
{
objects [i] = Instantiate (objectToGenerate, position, Quaternion.identity, parent);
if (objects [i] .GetComponent <CollideManager> (). IsTriggered)
{
Destroy (objects [i]);
}
else break;
}
The CollideManager component is attached to objectToGenerate. The isTriggered variable is true if the object intersects with another object. Here is the component code:
public class CollideManager: MonoBehaviour {
public bool isTriggered = false;
private void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Static")
{
IsTriggered = true;
}
}
}
But all this code does not work.
I guess that it's because unity does not have time to process a collision of a new object with the old ones in a zero period of time between this line:
objects [i] = Instantiate (objectToGenerate, position, Quaternion.identity, parent);
And this:
if (objects [i] .GetComponent <CollideManager> (). IsTriggered)
So I decided to change it all into a coroutine and add a delay:
objects [i] = Instantiate (objectToGenerate, position, Quaternion.identity, parent);
yield return new WaitForSeconds (0.5f);
if (objects [i] .GetComponent <CollideManager> (). IsTriggered)
{
Destroy (objects [i]);
}
else break;
But now
The game began to hang.
Objects appear right in front of the user, and in the most unexpected and inconvenient places.
I also tried to use WaitForFixedUpdate
instead of WaitForSeconds
, but it didn't work: objects were intersected with each other.
How to make it work?
P.S. Sorry for my English :)
Have you considered using the overlapping sphere function to check based on the bounds of the object whether or not something else exists in its place, aside from terrain of course. Then you can avoid redundant instantiations and don't need to waste memory resources by destroying them.
Do you mean this? https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
No, I haven't, but I'll try. thanks)