- Home /
Change transform.position.y in a loop
I am trying make a game that will generate a grid of blocks in start. This code makes them generate on x line, but when I try to add y in a loop and set it in the Vector3, it doesn't seem to work. *The problem is that it doesn't switch to 2nd line in y. using UnityEngine; using System.Collections;
public class GenerateTileyyy: MonoBehaviour {
public GameObject tile;
public float distanceBetweenTiles = 1.5f;
public float spawnSpeed = 0;
public float grid = 15;
public float x = 0;
public float y = 0;
// Use this for initialization
void Start () {
float x = transform.position.x;
float y = transform.position.y;
for (x=0; x < grid; x=x+1.5f) {
Instantiate (tile, new Vector3 (x, y, 0), Quaternion.identity);
if (x == 10f) {
x = 0;
y = y + 2;
}
}
}
}
It doesn't switch to 2nd line in the game screen. Just generates only 1st line/row.
You're declaring x (and also y) multiple times. Try using different variable names for each of them.
Answer by Uldeim · Nov 25, 2014 at 09:37 PM
You're declaring x and y twice, which is silly, but irrelevant.
Your main problem is that 1.5 *
6 is 9, and 1.5 *
7 is 10.5, so you're never going to get x == 10f. Actually, because float arithmetic is imprecise, it's a bad idea to test equality anyways (though 0.5f is actually exact, so it's not a big deal here).
Change your if to x > 10f
and you should be in good shape... or you would be, except it will actually cause an infinite loop, since x will then always be less than grid. While you could change the second argument of your for loop to y < grid
, it's weird and unnatural to have different variables in there.
I suggest instead that you use a slightly more popular pattern: Nested loops.
for (float x = 0; x < grid; x += 1.5f)
{
for (float y = 0; y < grid; y += 2f)
{
Instantiate(tile, new Vector3(x,y,0), Quaternion.identity);
}
}
This is a good answer, just a couple of quibbles: 1. your answer will draw the tiles Bottom->Top then Left->Right versus the way the OP was trying to draw them. 2. While it wasn't a factor here, declaring variables with the same name is a really bad practice that can lead to tremendous headaches down the road.
@FrostyNomad - Agreed on both points. To draw horz/vert ins$$anonymous$$d, just switch the order of the for loops.