Reputation: 107
So I have this piece of code that generates a 7x50 grid that falls down.
public class FieldController : MonoBehaviour
{
[SerializeField] private GameObject gridPrefab;
[SerializeField] private int rows = 50;
[SerializeField] private int columns = 7;
[SerializeField] private float tileSize = 1;
private GameObject tile;
private GameObject parentObject;
private float gridW;
private float gridH;
private float posX;
private float posY;
private void Start()
{
parentObject = new GameObject("Parent");
GenerateGrid();
}
private void Update()
{
MoveGridDown();
}
void GenerateGrid()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
tile = Instantiate(gridPrefab, parentObject.transform);
posX = j * tileSize;
posY = i * tileSize;
tile.transform.position = new Vector2(posX, posY);
}
}
SetParentToStart(parentObject);
}
void SetParentToStart(GameObject parent)
{
parent.transform.position = new Vector3(-columns / 2 + tileSize, rows / 10, 0);
}
void MoveGridDown()
{
parentObject.transform.position -= new Vector3(0, FallingObjectBehaviour.FallingSpeed * Time.deltaTime);
}
}
This is how it looks: https://i.sstatic.net/PuFOG.jpg
What I want to do is to be able to generate the new grid every time the previous one reaches the end so it would look like the grid is infinite.
I've tried to use extra GameObject for a parent and switch between them but the results were buggy. Is there any way to make it possible?
Upvotes: 0
Views: 1146
Reputation: 432
i believe you want to generate the next grid before it reaches the end, and i suggest a system where you have
GameObject gridPrefab;
GameObject grid;
Queue<GameObject> grids;
Transform camera;
Vector3 newPos = Vector3.zero;
Vector3 offset = new Vector3(0,0,50);
Quaternion forward = Quaternion.Euler(Vector3.forward);
int i = 0;
then you instantiate the new grid once camera is beyond "newPos", add it to the queue and destroy the last one.
if(newPos.z > camera.z)
{
newPos += offset;
grid = Instantiate(gridPrefab,newPos,forward);
grid.name = $"grid{++i}";
grids.Enqueue(grid);
Destroy(grids.Dequeue());
}
this is done without testing, let me know if makes sense to you, i can test it later if makes sense but is not working.
Upvotes: 1