Hi!
I’m using a for loop to spawn objects,and i would like to have x amount of space between the spawned objects.
But if i do it like this,it starts to make the given space bigger and bigger.
void Update()
{
randomSpace = Random.Range(minSpawnSpace, maxSpawnSpace);
}
for (int i = 0; i < length; i++)
{
randomNumber = PickANumber(-1, 1);
Vector3 pos = new Vector3(transform.position.x + randomNumber, transform.position.y, i * randomSpace);
int index = Random.Range(0, objects.Length);
cube = Instantiate(objects[index], pos, transform.rotation);
cube.transform.parent = transform;
}
I think it’s because when the “i” variable starts to get bigger the gap between the objects multiplying in a wrong way.
So i think if i could get the last spawned object’s position and added the random space to it’s transform.position.z,it would work but i don’t know how to do it.
Thanks in advance.
int index = Random.Range(0, objects.Length);
cube = Instantiate(objects[index], pos, transform.rotation);
You use an object that already has an offset as a base for instantiating another object. I wouldn’t be surprised if the instantiated object has the position pos + objects[index].transform.position.
Hm, I see, could you post the whole code, please? It is not very clear in your initial code what is what.
I had that weird exponentially increasing offsets in the past, too, I am confident that at some point, you use a transform of an object that already has an offset. If you post the whole code, I can run some quick tests myself.
Thanks, I used it and it doesn’t appear to increase the space, see the attachment. How does it look for you? I used a length of 100 with a space of 5. Even with setting minSpawnSpace and maxSpawnSpace to different values, to a range, didn’t change that.
With your spawn script, you create an array of two objects, every time with one being slightly off in x and the other one being slightly off in y. Between two of these cubes and two other ones, there is a random space in z direction. This random space is at least minSpawnSpace and no larger than maxSpawnSpace.
However, when I look at the screenshot that you posted, I see exactly that. I don’t understand why you see the right space to the left and right and a supposedly huge amount of space in the middle.
Do you not want cubes sharing the same x and y coordinates to be too far off from each other?
No the offsets on the x and y are good,but it seems to me that it’s leaving larger amount of spaces on the z axis than the maxSpawnSpace.But sometimes,as i drew on the picture,the spaces are the riight amount but sometimes it’s not.At least it’s seems like it.
You could log the difference in z between an previously spawned object and a just spawned object to see if it is true.
It could look something like this: