Currently in my game I have gotten chunks to load and unload well - except for one part. In order to find how close a player is to chunks, the planet class that controls the chunks checks every chunks distance to figure out which to load first. I know there is probably a much better way to do this, because when planets over 1,000 chunks load, there is a VERY noticeable freeze when the distances are calculated.
Current code:
public void FixedUpdate()
{
StartCoroutine(ChunkQueue());
timer = timer + 1;
if (timer > 20)
{
foreach (GameObject player in players)
{
int playerx = (int)player.transform.position.x;
int playery = (int)player.transform.position.y;
int playerz = (int)player.transform.position.z;
//Each chunk is 16x16 but since planets can have different sizes planetSize / 16 always returns the correct amount
? //Also for technical reasons planets start in the 1 position in the array, not 0
for (int x = 1; x <= planetSize / 16; x++)
{
for (int y = 1; y <= planetSize / 16; y++)
{
for (int z = 1; z <= planetSize / 16; z++)
{
float distance = Vector3.Distance(player.transform.position, new Vector3(this.transform.position.x + (x * 16), this.transform.position.y + (y * 16), this.transform.position.z + (z * 16)));
if (ischunkloaded[x, y, z] == true)
{
if (distance > 200)
{
ischunkloaded[x, y, z] = false;
UnloadChunk(planetchunks[x, y, z]);
}
}
if (ischunkloaded[x, y, z] == false)
{
if (distance < 200)
{
if (LoadDone == true)
{
toLoad.Add(new Vector4(x, y, z, Mathf.RoundToInt(distance)));
toLoad.Sort(delegate (Vector4 first, Vector4 second) { return first.w.CompareTo(second.w); });
}
}
}
}
}
}
}
timer = 0;
}
}