Search code examples
c#unity-game-enginerandomgameobject

How to instantiate GameObject at random collision free position?


I am making a game in Unity. I am instantiating (circle) GameObjects on random positions and it works well. What I am trying to do is to instantiate only on positions where there will be no overlapping with other GameObjects. No solution that I have found on the internet solved my problem so what should i do? Is this possible?


Solution

  • Ok. In order to detect if there is space for your circle you will need to use either a collider or a mathematical/volume equation. But whichever way you do this you will need to reference a position(transform x,y,z) to sample an area and determine if your circle can be spawned there.

    You could do one of the following:

    1. Create the object as you normaly would, but if there is a collision immediately destroy the object. Then spawn another.
    2. Move a spawner gameobject in a location which does the same check as above but only when it has been determined there is room for the circle do you spawn it. (edit) Then disable or move the spawner, you will only need one of these objects to do all your spawning.
    3. Have whichever class spawns the circles pick from an array of predefined positions(a vector 3 or existing gameobjects in the scene) then perform one of the checks above.

    It depends of your needs and how likely an overlap is.

    Hope it helps.