- Home /
A way to destroy these blocks faster?
im trying to destroy the chunk of blocks as quickly as they are instantiated. Basically blocks are destroyed and instantiated depending on the player's distance from the chunk. When blocks are instantiated, they quickly instantiate as if the entire chunk in instantiating at once. However, when it comes to destroying them, it seems that they are destroyed in flowing rows, like this (may not be a good image):
So the questions is, how do i destroy the blocks as quickly as they are being instanced? Does it have to do with using a foreach loop and a list? Here's the code:
Vector3 chunkCenter = new Vector3(transform.position.x + BlockData.chunkX / 2, BlockData.chunkY, transform.position.z + BlockData.chunkZ/2);
if(Vector3.Distance(chunkCenter,player.transform.position) > terrain.maxViewDistance) {
terrain.chunksToRender.Remove(transform);
foreach(Transform block in terrain.blockList) {
if(block != null) {
if(block.position.x >= transform.position.x && block.position.x < transform.position.x + terrain.blocksX) {
if(block.position.z >= transform.position.z && block.position.z < transform.position.z + terrain.blocksZ) {
Destroy (block.gameObject);
terrain.blockList.Remove(block);
}
}
}
}
} else if(!terrain.chunksToRender.Contains(transform)) {
terrain terrainScript = blockGenerator.GetComponent<terrain>();
terrainScript.renderChunk(transform);
terrain.chunksToRender.Add(transform);
}
Answer by aldonaletto · Sep 06, 2012 at 12:56 AM
You should not modify the list while iterating through it with foreach - this screws up the loop control, with unpredictable results. A good work around is to use a copy of the list in the foreach - this way you can safely remove elements from the original list. The List method [CopyTo][1] seems a good choice to make this copy:
... if(Vector3.Distance(chunkCenter,player.transform.position) > terrain.maxViewDistance) { terrain.chunksToRender.Remove(transform); // create a copy of blockList: Transform[] blocks = new Transform[terrain.blockList.Count]; terrain.blockList.CopyTo(blocks); // copy the list to the blocks array foreach (Transform block in blocks) { // use blocks in the foreach... ... // now you can safely delete blockList elements in the foreach: terrain.blockList.Remove(block); ...[1]: http://msdn.microsoft.com/en-us/library/t69dktcd.aspx
Awesome. I wonder why I can't keep my framerate above 60 even with this whole method working. It runs between 25 to 60 fps which may sound good but isn't since im working on a gtx 560 ti. which means regular cards wont perform well. I'll make that a seperate question which I'd love for you to check out :)