- Home /
How do you spawn multiple prefabs within a certain distance from each other from one spawn point?
Say I have four spawn points, and I want each spawn point to instantiate a random amount of rigidbody prefabs within a certain range of each other. I can currently instantiate one prefab per spawn point, so how would I go about doing this?
-Generate all within a certain distance of the spawn point, or is the distance between each Instantiated object the important thing?
-Are you looking for a formation like a grid, or spawned in a circle, or are you looking for random placement?
-Is this 2D (i.e. on a plane), or 3D (within a sphere).
Generate a random amount of prefabs within a certain distance of a spawn point.
Circular formation
This is on top of a 2d plane $$anonymous$$G spawning 3D prefabs on a gameobject named "ground"
Answer by HappyMoo · Jan 16, 2014 at 02:05 AM
Here's some code. Not tested in unity, so might include syntax errors, but you get the idea.
Vector3 spawnMidPoint = new Vector3(5,0,10);
int num = Random.Range(3,10);
float radius = 10;
float pi2 = 2*Mathf.PI;
for(int i = 0; i<num; i++)
{
Vector3 pos = spawnMidPoint + new Vector3(Mathf.Cos(i*pi2/num)*radius,0,Mathf.Sin(i*pi2/num)*radius)
Instantiate(prefab, pos, rot);
}
Answer by Deon-Cadme · Jan 16, 2014 at 12:39 AM
You calculate the position for each new instance of an object that you are spawning.
A good practice is also to make a collision check before spawning, just to make sure that no object ends up halfway in a wall or something. Another trick is also to define a radius or area around the spawn point where the objects are allowed to appear. That way, you can avoid a lot of collision checks.
Your answer
Follow this Question
Related Questions
How do I spawn an object under another moving object at random in C#? 1 Answer
How to spawn a new prefab when the last one was destroyed?? 2 Answers
Prevent object from spawning at a spawn point twice in a row? 3 Answers
prevent object from falling to the left side when instantiated (spawned) ? 1 Answer
SOLVED : Adding and retrieving instantiated objects from Array 1 Answer