Bioxent
1
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;
}
}
}
}
Uldeim
2
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);
}
}