[C#] Instantiate prefabs a set distance from one another infinitely with a limit

Hi all, I’ve been looking everywhere for an answer to this and I’ve tried everything I know but I just can seem to solve my problem.

Essentially, I’m trying to continuously (so probably within void Update) instantiate prefabs a set distance from one another as long as they will be within the view of the camera/player, so there isn’t an infinite amount of prefabs being spawned uselessly in the scene.

I’m not asking for a script to be written up for me, I’m just asking for some guidance or someone to point me in the right direction.


Get the distance between 2 objects in unity :

Vector3 distance = ObjectA.transform.position - ObjectB.transform.position;

Now, what you do with this is up to you, To get the “Length” of the vector, in 3D, you do :


You could compare that to a predetermined value to determine wether it’s off limit or not.

You could also take a single coordinate to make your measurements.

Spawning objects a certain distance from each other :

You can set a position to an object when instantiating it. Here’s a simple example:

public GameObject myPrefab;

void MyFunction()
     GameObject myPrefabInstance = GameObject.Instantiate(myPrefab, new Vector3(0,10,0), Quaternion.identity);

Now, what you can do, is keep a reference to the position of the last object instantiated, and add an “offset” to it. so it spawns at a certain distance from the last.

Vector3 lastPosition = new Vector3(0,0,0);
Vector3 offsetVector = new Vector3(0,1,0);

void MyFunction()
    GameObject myPrefabInstance = GameObject.Instantiate(myPrefab, lastPosition + offsetVector, Quaternion.identity);
    lastPosition = myPrefabInstance.position;

Now, this is all just examples to illustrate what i mean, You would need to add the function in a loop… with good conditions to stop it

Does this help ? If it doesn’t, i’ll update with more information.