I'm trying to procedurally generate tiles on the screen as soon as the level loads. This question pertains to making my algorithm as efficient as possible.
- What I was doing before: In the Update() function (this section of Update() function is only being called ONCE when the game starts), I was simply instantiating the tile 12,000 times on the screen to create the entire map for the game. In the following code, x[i] and y[i] are the grid co-ordinate values that I'm incrementing in another function.
Cons: Level takes a longer time to load. Pros: Once the level is loaded, fps stays consistent and high.
void Update()
{
if (loadThisSectionOnce = false)
{
loadThisSectionOnce = true;
for (int i = 0; i <= 12000; i++)
{
tiles[i] = Instantiate(tile, new Vector3(x[i], y[i], transform.rotation) as GameObject;
}
}
}
- What I am trying to now: I only want to have the tiles that are around the player get instantiated, and as the player roams around, the other tiles are instantiated henceforth so that as the game loads initially, not all the tiles are loaded at the same time (hence less loading time - more dynamic).
void Update()
{
var distance = Vector2.Distance(new Vector2(x[i], y[i], PlayerPosition);
if (distance < 20.0F)
{
for (int i = 0; i <= 12000; i++)
{
tiles[i] = Instantiate(tile, new Vector3(x[i], y[i], transform.rotation) as GameObject;
}
}
}
NOTE: This time there is no boolean variable to make sure that this section of the Update() function is called only ONCE, but it's being called every frame.
Pros: Yay! ONLY the tiles which are around the player are generated + level loading time is super fast. Cons: There is a FOR loop (iteration upto 12000!) being called every frame because of which the frames per second (fps) is very LOW while the game is running.
What do I need?: How do make my second attempt more efficient? Is there any way? I appreciate the help!