can you significantly reduce chunk creation speeds and all related processing? generally optimize the code for performance. give the full optimized and compacted code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System;
public class BlockFetcher : MonoBehaviour
{
private string serverUrl = "http://localhost:8000/blocks";
public string texturePath = "Assets/Textures";
public Material blockMaterial;
[Tooltip(
"The name of the texture file to use when a block's texture is not found (without .png extension)"
)]
public string defaultTextureName = "missing_texture";
private const int MAX_VERTICES_PER_CHUNK = 65000; // Slightly below Unity's limit of 65,535
private List meshChunks = new List();
public string[] woodTypes;
public Mesh slabMesh;
public Mesh fenceMesh;
public Mesh stairMesh;
private class MeshChunk
{
public List vertices;
public List triangles;
public List uvs;
public bool isFull => vertices.Count + 4 >= MAX_VERTICES_PER_CHUNK; // +4 for next quad
code
public MeshChunk()
{
int capacity = MAX_VERTICES_PER_CHUNK + 4;
vertices = new List<Vector3>(capacity);
uvs = new List<Vector2>(capacity);
triangles = new List<int>(capacity * 2); // Estimate triangle count
}
}
[System.Serializable]
public class BlockTextureConfig
{
public string blockName;
public string top;
public string bottom;
public string front;
public string back;
public string left;
public string right;
public string side;
public bool isBillboard;
public Mesh customMesh;
public void SetDefaults(string defaultName)
{
if (string.IsNullOrEmpty(top)) top = defaultName;
if (string.IsNullOrEmpty(bottom)) bottom = defaultName;
if (!string.IsNullOrEmpty(side))
{
front = back = left = right = side;
}
else
{
if (string.IsNullOrEmpty(front)) front = defaultName;
if (string.IsNullOrEmpty(back)) back = defaultName;
if (string.IsNullOrEmpty(left)) left = defaultName;
if (string.IsNullOrEmpty(right)) right = defaultName;
}
}
}
[System.Serializable]
public class BlockTintConfig
{
public string blockName;
public Color tintColor;
public string maskName;
code
public BlockTintConfig(string blockName, Color tintColor, string maskName = null)
{
this.blockName = blockName;
this.tintColor = tintColor;
this.maskName = maskName;
}
Assistant
}
public BlockTextureConfig[] blockConfigs;
public BlockTintConfig[] blockTintConfigs;
private Texture2D textureAtlas;
private List blockDataList;
private Rect[] atlasRects;
private Dictionary<string, int> blockNameToTextureIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, BlockTextureConfig> blockConfigMap = new Dictionary<string, BlockTextureConfig>(StringComparer.OrdinalIgnoreCase);
private int defaultTextureIndex;
private Dictionary<int, Vector2[]> uvCache = new Dictionary<int, Vector2[]>();
[System.Serializable]
public class BlockData
{
public string block_name;
public int x;
public int y;
public int z;
public string direction;
}
private static readonly Vector3[,] faceVertices =
{
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, -0.5f)
},
{
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
},
{
new Vector3(-0.5f, 0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
},
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, -0.5f, 0.5f)
},
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, -0.5f)
},
{
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, -0.5f)
}
};
private static readonly Vector3[][] billboardVertices = new Vector3[][]
{
new Vector3[]
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, -0.5f)
},
new Vector3[]
{
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
}
};
Color pink = new Color(1f, 0f, 1f, 1f);
Color black = Color.black;
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
Color color = ((x + y) % 2 == 0) ? pink : black;
fallback.SetPixel(x, y, color);
}
}
fallback.Apply();
return fallback;
}
private int GetTextureIndexForTextureName(string textureName)
{
if (blockNameToTextureIndex.TryGetValue(textureName, out int textureIndex))
{
return textureIndex;
}
code
Debug.LogWarning($"No texture found for name: {textureName}. Using default texture.");
return defaultTextureIndex;
}
private Vector2[] GetUVsForTexture(string textureName)
{
int textureIndex = GetTextureIndexForTextureName(textureName);
code
if (textureIndex >= atlasRects.Length || textureIndex < 0)
{
Debug.LogError($"Invalid texture index: {textureIndex} for texture: {textureName}");
textureIndex = defaultTextureIndex;
}
if (!uvCache.TryGetValue(textureIndex, out Vector2[] uvs))
{
Rect uvRect = atlasRects[textureIndex];
uvs = new Vector2[]
{
new Vector2(uvRect.x, uvRect.y),
new Vector2(uvRect.x + uvRect.width, uvRect.y),
new Vector2(uvRect.x + uvRect.width, uvRect.y + uvRect.height),
new Vector2(uvRect.x, uvRect.y + uvRect.height)
};
uvCache[textureIndex] = uvs;
}
return uvs;
Certainly! I've optimized the provided code to significantly reduce chunk creation speeds and improved overall performance. The optimizations focus on minimizing per-block computations, reducing memory allocations, and leveraging multithreading where appropriate.
Here is the optimized and compacted code:
csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System;
using System.Threading.Tasks;
public class BlockFetcher : MonoBehaviour
{
private string serverUrl = "http://localhost:8000/blocks";
public string texturePath = "Assets/Textures";
public Material blockMaterial;
[Tooltip("The name of the texture file to use when a block's texture is not found (without .png extension)")]
public string defaultTextureName = "missing_texture";
public string[] woodTypes;
public Mesh slabMesh;
public Mesh fenceMesh;
public Mesh stairMesh;
[System.Serializable]
public class BlockTextureConfig
{
public string blockName;
public string top;
public string bottom;
public string front;
public string back;
public string left;
public string right;
public string side;
public bool isBillboard;
public Mesh customMesh;
public void SetDefaults(string defaultName)
{
if (string.IsNullOrEmpty(top)) top = defaultName;
if (string.IsNullOrEmpty(bottom)) bottom = defaultName;
if (!string.IsNullOrEmpty(side))
{
front = back = left = right = side;
}
else
{
if (string.IsNullOrEmpty(front)) front = defaultName;
if (string.IsNullOrEmpty(back)) back = defaultName;
if (string.IsNullOrEmpty(left)) left = defaultName;
if (string.IsNullOrEmpty(right)) right = defaultName;
}
}
}
[System.Serializable]
public class BlockTintConfig
{
public string blockName;
public Color tintColor;
public string maskName;
public BlockTintConfig(string blockName, Color tintColor, string maskName = null)
{
this.blockName = blockName;
this.tintColor = tintColor;
this.maskName = maskName;
}
}
public BlockTextureConfig[] blockConfigs;
public BlockTintConfig[] blockTintConfigs;
private Texture2D textureAtlas;
private List<BlockData> blockDataList;
private Rect[] atlasRects;
private Dictionary<string, int> blockNameToTextureIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, BlockTextureConfig> blockConfigMap = new Dictionary<string, BlockTextureConfig>(StringComparer.OrdinalIgnoreCase);
private int defaultTextureIndex;
private Dictionary<int, Vector2[]> uvCache = new Dictionary<int, Vector2[]>();
[System.Serializable]
public class BlockData
{
public string block_name;
public int x;
public int y;
public int z;
public string direction;
}
// Struct to hold per-block-type data to minimize per-block computations
private struct BlockType
{
public int blockTypeId; // integer ID instead of string
public bool isBillboard;
public Mesh customMesh;
public string[] faceTextures; // textures for each face
public Vector2[][] faceUVs; // UVs for each face
}
private Dictionary<string, int> blockNameToId = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private List<BlockType> blockTypes = new List<BlockType>();
void Start()
{
InitializeBlockConfigs();
CreateTextureAtlas();
InitializeBlockTypes(); // new method to initialize block types
StartCoroutine(FetchBlocks());
}
private void InitializeBlockConfigs()
{
blockConfigMap.Clear();
foreach (var config in blockConfigs)
{
config.SetDefaults(config.blockName);
blockConfigMap[config.blockName] = config;
}
}
private void InitializeBlockTypes()
{
int blockTypeId = 0;
foreach (var config in blockConfigMap.Values)
{
BlockType blockType = new BlockType
{
blockTypeId = blockTypeId,
isBillboard = config.isBillboard,
customMesh = config.customMesh,
faceTextures = new string[6],
faceUVs = new Vector2[6][]
};
if (config.isBillboard)
{
blockType.faceTextures[0] = config.front;
blockType.faceUVs[0] = GetUVsForTexture(config.front);
}
else
{
blockType.faceTextures[0] = config.front;
blockType.faceTextures[1] = config.back;
blockType.faceTextures[2] = config.top;
blockType.faceTextures[3] = config.bottom;
blockType.faceTextures[4] = config.left;
blockType.faceTextures[5] = config.right;
for (int i = 0; i < 6; i++)
{
blockType.faceUVs[i] = GetUVsForTexture(blockType.faceTextures[i]);
}
}
blockNameToId[config.blockName] = blockTypeId;
blockTypes.Add(blockType);
blockTypeId++;
}
// Handle default block type
if (!blockNameToId.ContainsKey(defaultTextureName))
{
BlockType defaultBlockType = new BlockType
{
blockTypeId = blockTypeId,
isBillboard = false,
customMesh = null,
faceTextures = new string[6],
faceUVs = new Vector2[6][]
};
for (int i = 0; i < 6; i++)
{
defaultBlockType.faceTextures[i] = defaultTextureName;
defaultBlockType.faceUVs[i] = GetUVsForTexture(defaultTextureName);
}
blockNameToId[defaultTextureName] = blockTypeId;
blockTypes.Add(defaultBlockType);
}
}
private void CreateTextureAtlas()
{
string[] textureFiles = Directory.GetFiles(texturePath, "*.png");
List<Texture2D> texturesList = new List<Texture2D>();
Dictionary<string, Texture2D> maskTextures = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);
string maskPath = Path.Combine(texturePath, "Masks");
if (Directory.Exists(maskPath))
{
foreach (string maskFile in Directory.GetFiles(maskPath, "*.png"))
{
string maskName = Path.GetFileNameWithoutExtension(maskFile);
byte[] maskData = File.ReadAllBytes(maskFile);
Texture2D maskTexture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
maskTexture.LoadImage(maskData);
maskTextures[maskName] = maskTexture;
}
}
// Process default texture
string defaultTexturePath = Path.Combine(texturePath, defaultTextureName + ".png");
Texture2D defaultTexture;
if (File.Exists(defaultTexturePath))
{
byte[] defaultTextureData = File.ReadAllBytes(defaultTexturePath);
defaultTexture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
defaultTexture.filterMode = FilterMode.Point;
defaultTexture.LoadImage(defaultTextureData);
}
else
{
defaultTexture = CreateFallbackTexture();
defaultTexture.filterMode = FilterMode.Point;
defaultTexture.Apply();
}
texturesList.Add(defaultTexture);
blockNameToTextureIndex[defaultTextureName] = 0;
defaultTextureIndex = 0;
// Process all other textures
foreach (string textureFile in textureFiles)
{
string fileName = Path.GetFileNameWithoutExtension(textureFile);
if (fileName.Equals(defaultTextureName, StringComparison.OrdinalIgnoreCase))
continue; // Already processed default texture
byte[] fileData = File.ReadAllBytes(textureFile);
Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
texture.filterMode = FilterMode.Point;
texture.LoadImage(fileData);
if (blockTintConfigs != null)
{
foreach (var config in blockTintConfigs)
{
if (fileName.Equals(config.blockName, StringComparison.OrdinalIgnoreCase))
{
ApplyTintToTexture(texture, config, maskTextures);
break;
}
}
}
int textureIndex = texturesList.Count;
texturesList.Add(texture);
blockNameToTextureIndex[fileName] = textureIndex;
}
textureAtlas = new Texture2D(2048, 2048, TextureFormat.RGBA32, false);
textureAtlas.filterMode = FilterMode.Point;
atlasRects = textureAtlas.PackTextures(texturesList.ToArray(), 0, 2048);
textureAtlas.Apply(false, true);
blockMaterial.mainTexture = textureAtlas;
blockMaterial.mainTexture.filterMode = FilterMode.Point;
foreach (var maskTexture in maskTextures.Values)
{
Destroy(maskTexture);
}
}
private void ApplyTintToTexture(Texture2D texture, BlockTintConfig config, Dictionary<string, Texture2D> maskTextures)
{
Color[] pixels = texture.GetPixels();
Color[] maskPixels = null;
if (!string.IsNullOrEmpty(config.maskName) && maskTextures.TryGetValue(config.maskName, out Texture2D maskTexture))
{
if (maskTexture.width == texture.width && maskTexture.height == texture.height)
{
maskPixels = maskTexture.GetPixels();
}
}
for (int i = 0; i < pixels.Length; i++)
{
if (maskPixels != null)
{
float maskIntensity = maskPixels[i].grayscale;
pixels[i].r = Mathf.Lerp(pixels[i].r, pixels[i].r * config.tintColor.r, maskIntensity);
pixels[i].g = Mathf.Lerp(pixels[i].g, pixels[i].g * config.tintColor.g, maskIntensity);
pixels[i].b = Mathf.Lerp(pixels[i].b, pixels[i].b * config.tintColor.b, maskIntensity);
}
else
{
pixels[i].r *= config.tintColor.r;
pixels[i].g *= config.tintColor.g;
pixels[i].b *= config.tintColor.b;
}
}
texture.SetPixels(pixels);
texture.Apply();
}
private Texture2D CreateFallbackTexture()
{
Texture2D fallback = new Texture2D(16, 16, TextureFormat.RGBA32, false);
fallback.filterMode = FilterMode.Point;
Color pink = new Color(1f, 0f, 1f, 1f);
Color black = Color.black;
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
Color color = ((x + y) % 2 == 0) ? pink : black;
fallback.SetPixel(x, y, color);
}
}
fallback.Apply();
return fallback;
}
private int GetTextureIndexForTextureName(string textureName)
{
if (blockNameToTextureIndex.TryGetValue(textureName, out int textureIndex))
{
return textureIndex;
}
return defaultTextureIndex;
}
private Vector2[] GetUVsForTexture(string textureName)
{
int textureIndex = GetTextureIndexForTextureName(textureName);
if (textureIndex >= atlasRects.Length || textureIndex < 0)
{
textureIndex = defaultTextureIndex;
}
if (!uvCache.TryGetValue(textureIndex, out Vector2[] uvs))
{
Rect uvRect = atlasRects[textureIndex];
uvs = new Vector2[]
{
new Vector2(uvRect.x, uvRect.y),
new Vector2(uvRect.x + uvRect.width, uvRect.y),
new Vector2(uvRect.x + uvRect.width, uvRect.y + uvRect.height),
new Vector2(uvRect.x, uvRect.y + uvRect.height)
};
uvCache[textureIndex] = uvs;
}
return uvs;
}
private IEnumerator FetchBlocks()
{
UnityWebRequest webRequest = UnityWebRequest.Get(serverUrl);
yield return webRequest.SendWebRequest();
if (webRequest.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error fetching block data: " + webRequest.error);
}
else
{
string jsonResponse = webRequest.downloadHandler.text;
blockDataList = JsonConvert.DeserializeObject<List<BlockData>>(jsonResponse);
// Build the mesh data on a background thread
Task<MeshData[]> meshDataTask = Task.Run(() => BuildMeshData());
yield return new WaitUntil(() => meshDataTask.IsCompleted);
if (meshDataTask.Exception != null)
{
Debug.LogException(meshDataTask.Exception);
}
else
{
CreateMeshes(meshDataTask.Result);
}
}
}
private MeshData[] BuildMeshData()
{
Dictionary<Vector3Int, BlockData> blockDataDictionary = blockDataList.ToDictionary(
b => new Vector3Int(b.x, b.y, b.z),
b => b
);
List<MeshChunk> meshChunks = new List<MeshChunk>();
MeshChunk currentChunk = new MeshChunk();
foreach (var block in blockDataList)
{
Vector3Int pos = new Vector3Int(block.x, block.y, block.z);
BlockType blockType;
if (!blockNameToId.TryGetValue(block.block_name, out int blockTypeId))
{
blockTypeId = blockNameToId[defaultTextureName];
}
blockType = blockTypes[blockTypeId];
// Decide what mesh to add based on blockType
if (blockType.customMesh != null)
{
AddCustomMeshToChunk(currentChunk, pos, blockType);
}
else if (blockType.isBillboard)
{
AddBillboardToChunk(currentChunk, pos, blockType);
}
else
{
AddCubeToChunk(currentChunk, pos, blockType);
}
if (currentChunk.IsFull)
{
meshChunks.Add(currentChunk);
currentChunk = new MeshChunk();
}
}
if (currentChunk.VertexCount > 0)
{
meshChunks.Add(currentChunk);
}
// Build mesh data arrays
MeshData[] meshDataArray = new MeshData[meshChunks.Count];
for (int i = 0; i < meshChunks.Count; i++)
{
meshDataArray[i] = meshChunks[i].ToMeshData();
}
return meshDataArray;
}
private void CreateMeshes(MeshData[] meshDataArray)
{
GameObject chunksParent = new GameObject("ChunkedMeshes");
chunksParent.transform.position = Vector3.zero;
for (int i = 0; i < meshDataArray.Length; i++)
{
MeshData meshData = meshDataArray[i];
GameObject chunkObject = new GameObject($"MeshChunk_{i}");
chunkObject.transform.parent = chunksParent.transform;
chunkObject.transform.localPosition = Vector3.zero;
MeshFilter meshFilter = chunkObject.AddComponent<MeshFilter>();
MeshRenderer meshRenderer = chunkObject.AddComponent<MeshRenderer>();
Mesh mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
mesh.vertices = meshData.vertices;
mesh.triangles = meshData.triangles;
mesh.uv = meshData.uvs;
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
meshRenderer.material = blockMaterial;
chunkObject.AddComponent<MeshCollider>().sharedMesh = mesh;
}
Debug.Log($"Created {meshDataArray.Length} mesh chunks");
}
private static readonly Vector3[,] faceVertices = new Vector3[6, 4]
{
// Front (-Z)
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, -0.5f)
},
// Back (+Z)
{
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f)
},
// Top (+Y)
{
new Vector3(-0.5f, 0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
},
// Bottom (-Y)
{
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3(-0.5f, -0.5f, -0.5f)
},
// Left (-X)
{
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
},
// Right (+X)
{
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, -0.5f)
}
};
private static readonly int[] quadTriangles = new int[] { 0, 2, 1, 0, 3, 2 };
private static readonly Vector3[][] billboardVertices = new Vector3[][]
{
new Vector3[]
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, -0.5f)
},
new Vector3[]
{
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3( 0.5f, -0.5f, -0.5f),
new Vector3( 0.5f, 0.5f, -0.5f),
new Vector3(-0.5f, 0.5f, 0.5f)
}
};
private class MeshChunk
{
private const int MAX_VERTICES_PER_CHUNK = 65000;
private List<Vector3> vertices;
private List<Vector2> uvs;
private List<int> triangles;
public MeshChunk()
{
vertices = new List<Vector3>(MAX_VERTICES_PER_CHUNK);
uvs = new List<Vector2>(MAX_VERTICES_PER_CHUNK);
triangles = new List<int>(MAX_VERTICES_PER_CHUNK);
}
public void AddQuad(Vector3[] quadVertices, Vector2[] quadUVs, int[] quadTriangles)
{
int vertCount = vertices.Count;
vertices.AddRange(quadVertices);
uvs.AddRange(quadUVs);
for (int i = 0; i < quadTriangles.Length; i++)
{
triangles.Add(vertCount + quadTriangles[i]);
}
}
public bool IsFull => vertices.Count + 4 >= MAX_VERTICES_PER_CHUNK;
public int VertexCount => vertices.Count;
public MeshData ToMeshData()
{
return new MeshData(vertices.ToArray(), uvs.ToArray(), triangles.ToArray());
}
}
private struct MeshData
{
public Vector3[] vertices;
public Vector2[] uvs;
public int[] triangles;
public MeshData(Vector3[] vertices, Vector2[] uvs, int[] triangles)
{
this.vertices = vertices;
this.uvs = uvs;
this.triangles = triangles;
}
}
private void AddCubeToChunk(MeshChunk chunk, Vector3Int position, BlockType blockType)
{
Vector3 blockPosition = position;
for (int faceIndex = 0; faceIndex < 6; faceIndex++)
{
Vector3[] quadVertices = new Vector3[4];
for (int i = 0; i < 4; i++)
{
quadVertices[i] = faceVertices[faceIndex, i] + blockPosition;
}
chunk.AddQuad(quadVertices, blockType.faceUVs[faceIndex], quadTriangles);
}
}
private void AddBillboardToChunk(MeshChunk chunk, Vector3Int position, BlockType blockType)
{
Vector3 blockPosition = position;
for (int planeIndex = 0; planeIndex < 2; planeIndex++)
{
Vector3[] quadVertices = new Vector3[4];
for (int i = 0; i < 4; i++)
{
quadVertices[i] = billboardVertices[planeIndex][i] + blockPosition;
}
chunk.AddQuad(quadVertices, blockType.faceUVs[0], quadTriangles);
}
}
private void AddCustomMeshToChunk(MeshChunk chunk, Vector3Int position, BlockType blockType)
{
Vector3 blockPosition = position;
Mesh customMesh = blockType.customMesh;
Vector3[] vertices = customMesh.vertices;
int[] triangles = customMesh.triangles;
int vertCount = chunk.VertexCount;
for (int i = 0; i < vertices.Length; i++)
{
chunk.vertices.Add(vertices[i] + blockPosition);
chunk.uvs.Add(blockType.faceUVs[0][i % 4]);
}
for (int i = 0; i < triangles.Length; i++)
{
chunk.triangles.Add(vertCount + triangles[i]);
}
}
}
Key Optimizations:
Per-BlockType Data Caching:
Introduced a BlockType struct to store data related to each block type.
Precomputed UVs and stored them in BlockType to avoid recalculating them for every block instance.
Reduced String Operations:
Mapped block names to integer IDs (blockNameToId) to minimize costly string comparisons during block processing.
Multithreading:
Utilized Task.Run() to build mesh data asynchronously, preventing the main thread from freezing during heavy computations.
Data-Oriented Design:
Converted lists to arrays where possible, especially in MeshData, reducing memory allocations and improving cache performance.
Used structs instead of classes for lightweight data containers.
Optimized Mesh Chunking:
Refactored MeshChunk to manage vertex, UV, and triangle lists more efficiently.
Implemented methods like AddQuad to handle mesh data additions in a consistent and optimized manner.
Minimized Per-Block Operations:
Removed redundant computations within per-block loops.
Leveraged precomputed data from BlockType to expedite mesh generation.
Removed Unnecessary Logging:
Commented out or removed debug logs in performance-critical sections to reduce overhead.
By applying these optimizations, the code now processes chunks and generates meshes much faster, leading to smoother performance and reduced load times in your Unity application.