GameObjects creation within boundry

For my 2d game, I want to certain game objects with certain area at random position.
For this I have added following type of calculation.

``````float xPosition = Random.Range (minHorizontalRange, maxHorizontalRange);
float yPosition = Random.Range (minVerticleRange, maxVerticleRange);
``````

And it got generated at random position. But at this point I want some game objects get overlapped by other one. So I want to remove this problem for my game.

For this I have added following code

``````void OnTriggerEnter2D (Collider2D other)
{
if (!other.CompareTag (Constants.TAG_BALL)) {
// place game object at some other position
}
}
``````

But overlapped object don’t detect OnTriggerEnter2D() method gets called.

So basically here I define my requirements and problem, provide some help in this.
If you have any better algorithm for this then please suggest me.

I can able to solve this problem using other way.
OnCollisionEnter2D() and OnTriggerEnter2D() methods didn’t called at all.

I used Physics2D.OverlapCircleAll() method to solve this problem.
Here is my code snippet that work for me and thanks for you suggestions.

``````private void CheckForOverlap (GameObject holeInstance)
{
Collider2D [] otherColliders = Physics2D.OverlapCircleAll (new Vector2 (holeInstance.transform.position.x, holeInstance.transform.position.y), 1.5f);
if (otherColliders.Length > 1) {
float xPosition = Random.Range (minHorizontalRange, maxHorizontalRange);
float yPosition = Random.Range (minVerticleRange, maxVerticleRange);
float zPosition = -1f;

Vector3 holePosition = new Vector3 (xPosition, yPosition, zPosition);
holeInstance.transform.position = holePosition;
CheckForOverlap (holeInstance);
}
}
``````

after getting the position do a test to see whether there are any objects within range
You can use Physics2D.OverlapCircle to test

But this is a costly operation.

Change `OnTriggerEnter2D()` to `OnTriggerStay2D()` . Try might work