- Home /
Instantiate game objects at random positions
Hello! There are several questions like mine but they did not help me. I am tiring to instantiate 'maxNumOfGreenCicrcle' game objects at random positions but they should not collide with any other game objects.
public void InstantiateCircles()
{
for (int i = 1; i < maxNumOfGreenCicrcle; i++)
{
Instantiate(greenCircle, new Vector2(Random.Range(-randomXRange, randomXRange), Random.Range(-randomYRange, randomYRange)) , Quaternion.identity);
}
}
Answer by tormentoarmagedoom · Apr 01, 2020 at 02:09 PM
Create a prefab for other objects detection. Before instantiate your objects, instantiate that detector, and if do not detect anything, destroy it and instantiate your object there.
IF doens know how to do something of this, research about that specyfic function.
You should use
Instantiate()
Destroy()
OnTriggerStay()
Random.Range()
It is not a valid way to solve my question because of game logic there are some late run-time object instantiations.
Answer by onuregeunaldi1 · Apr 01, 2020 at 02:19 PM
It is not a valid way to solve my question because of game logic there are some late run-time object instantiations.
Answer by unidad2pete · Apr 01, 2020 at 05:14 PM
Hi, try to check colisions with spherecast before instantiate your prefab. https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html Get the random position, cast the sphere Ray with his origin on the positivo and you range desired to find colisions. If the Ray has colisions, only call another random psiton agai.
Your answer
![](https://koobas.hobune.stream/wayback/20220612230245im_/https://answers.unity.com/themes/thub/images/avi.jpg)