Hi so I’m new to unity and I’m currently working on making an infinite flat plane made up of blocks using chunk to determine render distance, however this is three main problems with my code that i cant figure out why its happening.
- Countless more blocks overlap and spawn on each other than needed
- The Loading of the chunks/ blocks don’t spawn around the player however spawn to the side of the player
- Due to the amount of extrablocks spawning framerate drops down to about 5 frames
Image of the problem
public class Chunk : MonoBehaviour
{
public GameObject ChunkManager;
public GameObject ObjectCord;
public int chunksize;
private int CurrentChunkX;
private int RawX;
private int CurrentChunkZ;
private int RawZ;
[SerializeField] int Maxchunks; // render distance
// Update is called once per frame
void Update()
{
List<string> LoadedList = new List<string>();
RawZ = (int)(Mathf.Floor(ObjectCord.transform.position.z)); // rounds down
RawX = (int)(Mathf.Floor(ObjectCord.transform.position.x));
//checks if RawX or RawZ is not 0, so when divided later errors dont popup
if (RawZ != 0)
{
CurrentChunkZ = (RawZ / chunksize);
}
else
{
CurrentChunkZ = 1;
}
if (RawX != 0)
{
CurrentChunkX = (RawX / chunksize);
}
else
{
CurrentChunkX = 1;
}
for (int p = (CurrentChunkX - (Maxchunks / 2)); p < Maxchunks; p++) // the X value on the 2d chunk loading table, made to be half so it loads around the player not in front
{
for (int o = (CurrentChunkZ - (Maxchunks / 2)); o < Maxchunks; o++) // the z value of the chunks
{
string temp = ("X:" + p + ", Z:" + o);
if (!LoadedList.Contains("X:" + p + ", Z:" + o)) //check if its not already added to the loaded list
{
LoadedList.Add(temp); // adds to loadedlist Chunks
int LoadChunkX = p * chunksize;
int LoadChunkY = o * chunksize;
chunkload(LoadChunkX, LoadChunkY); // starts loading in that chunk
}
else
{
}
}
}
}
void chunkload(int x, int y)
{
// places a block in each block position at each chunk
for (int PlacerX = 0; PlacerX < chunksize; PlacerX++)
{
for (int PlacerY = 0; PlacerY < chunksize; PlacerY++)
{
//clones block and fills
GameObject BoxClone = Instantiate(ChunkManager, new Vector3(x + PlacerX, ChunkManager.transform.position.y, y + PlacerY), ChunkManager.transform.rotation);
BoxClone.name = "Box" + x + y;
}
}
}
}
Heres is what the flow sheet looks like for both functions
Any input or help would be amazing thank you.