- Home /
Instantiate objects at random positions on axis
What's the code to instantiate 4 clones of an object at 4 different positions on an axis? I tryed
Instantiate(enemy, Vector3(Random.Range(-10,10),0,15), transform.rotation);
but it doesn't work since the x value, even if it's random, is still a single value. How can i tell Unity to choose four different values (beetween -10 and 10) of the x axis?
Not quite sure what you want here - if you call this code 4 times you will get 4 different values - did you want to ensure that no 2 values were the same?
I wanted to know if there is another solution than creating 4 different Vector3 values and writing 4 times this code. Anyway, yes, how can i ensure that each of the 4 Vector3 values is different from the other ones?
Answer by Mz3D · Jul 11, 2012 at 08:51 PM
I wanted to know if there is another solution than creating 4 different Vector3 values and writing 4 times this code. Anyway, yes, how can i ensure that each of the 4 Vector3 values is different from the other ones?
Answer by TowerOfBricks · Jul 11, 2012 at 03:20 PM
The chance to get two identical floating point numbers from Random.value (or Random.Range) is practically zero. However they might turn out to be really close, so I think you want some margin to make sure it isn't within some distance to the other points.
int count = 4;
float range = 10;
float margin = 1;
if (count*margin >= range*2) throw new System.Exception ("There is no possible distribution of points");
Vector3[] arr = new Vector3[count];
for (int i=0;i<count;i++) {
bool close = false;
do {
close = false;
arr[i] = new Vector3 (Random.Range (-range,range),0,15);
for (int j=0;j<i;j++) if ((arr[i]-arr[j]).sqrMagnitude < margin*margin) { close = true; break; }
} while (close);
Instantiate(enemy, arr[i], transform.rotation);
}
This code will create [count] enemies at random positions spaced at least [margin] apart at positions ranging from -[range] to [range] on the x-axis. It will also work if you expand the randomness to more than one axis. The code is written in C#. I hope I haven't made any mistakes (I typed it directly in the browser).
Your answer
Follow this Question
Related Questions
Object movement - undesired effects 1 Answer
How to Add Y Axis Offset to transform.localPosition on an Instantiated Prefab? 2 Answers
Randomizing a selection from an array 1 Answer
Are there more options to rotation 'Space' relativity? 1 Answer
Calculate Vector3 for rotation or just change pivot; 0 Answers