Unity C# - Spawning GameObjects randomly around a point

Mayron picture Mayron · Jan 8, 2016 · Viewed 9.5k times · Source

I am not sure how to approach this problem or whether there are any built in Unity functions that can help with this problem so any advice is appreciated.

Here is an image that'll help describe what I want to do: enter image description here

I want to spawn Game Objects around a given point within the limits of a set radius. However their position in this radius should be randomly selected. This position should have the same Y axis as the origin point (which is on the ground). The next main problem is that each object should not clash and overlap another game object and should not enter their personal space (the orange circle).

My code so far isn't great:

public class Spawner : MonoBehaviour {

    public int spawnRadius = 30; // not sure how large this is yet..
    public int agentRadius = 5; // agent's personal space
    public GameObject agent; // added in Unity GUI

    Vector3 originPoint;    

    void CreateGroup() {
        GameObject spawner = GetRandomSpawnPoint ();        
        originPoint = spawner.gameObject.transform.position;        

        for (int i = 0; i < groupSize; i++) {           
            CreateAgent ();
        }
    }

    public void CreateAgent() {
        float directionFacing = Random.Range (0f, 360f);

        // need to pick a random position around originPoint but inside spawnRadius
        // must not be too close to another agent inside spawnRadius

        Instantiate (agent, originPoint, Quaternion.Euler (new Vector3 (0f, directionFacing, 0f)));
    }
}

Thank you for any advice you can offer!

Answer

Hamza Hasan picture Hamza Hasan · Jan 8, 2016

For personal space you can use colliders to avoid overlapping.

For spawning in circle you can use Random.insideUnitSphere. You can modify your method as,

 public void CreateAgent() {
        float directionFacing = Random.Range (0f, 360f);

        // need to pick a random position around originPoint but inside spawnRadius
        // must not be too close to another agent inside spawnRadius
        Vector3 point = (Random.insideUnitSphere * spawnRadius) + originPoint;
        Instantiate (agent, point, Quaternion.Euler (new Vector3 (0f, directionFacing, 0f)));
    }

Hope this helps you.