public void RebuildMesh() { if (_mesh == null) { Debug.LogError("Mesh asset is missing."); return; } _mesh.Clear(); // Build a icosphere and subdivide it. IcosphereBuilder ib = new IcosphereBuilder(); for (var i = 0; i < _subdivision; i++) ib.Subdivide(); // Make vertex arrays. var vc = ib.vertexCache; var vcount = 3 * vc.triangles.Count; var va1 = new List<Vector3>(vcount); // vertex position var va2 = new List<Vector3>(vcount); // previous vertex position var va3 = new List<Vector3>(vcount); // next vertex position foreach (var t in vc.triangles) { var v1 = vc.vertices[t.i1]; var v2 = vc.vertices[t.i2]; var v3 = vc.vertices[t.i3]; va1.Add(v1); va2.Add(v2); va3.Add(v3); va1.Add(v2); va2.Add(v3); va3.Add(v1); va1.Add(v3); va2.Add(v1); va3.Add(v2); } // Rebuild the mesh asset. _mesh.SetVertices(va1); _mesh.SetUVs(0, va2); _mesh.SetUVs(1, va3); _mesh.SetIndices( vc.MakeIndexArrayForFlatMesh(), MeshTopology.Triangles, 0); _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 1000); _mesh.Optimize(); _mesh.UploadMeshData(true); }
void RebuildMesh() { if (_mesh) DestroyImmediate(_mesh); // Make an icosphere. IcosphereBuilder ib = new IcosphereBuilder(); for (var i = 0; i < _subdivision; i++) ib.Subdivide(); // Vertex array. var vc = ib.vertexCache; var vertices = new Vector3[vc.triangles.Count * 6]; var colors = new Color[vc.triangles.Count * 6]; // Make triangle scales. var offs = 0; foreach (var t in vc.triangles) { // Vertices on the original triangle. var v1 = vc.vertices[t.i1]; var v2 = vc.vertices[t.i2]; var v3 = vc.vertices[t.i3]; // Get the center of mass and encode it to a color. var cc = (v1 + v2 + v3) * 0.3333333f; var c = new Color(cc.x, cc.y, cc.z, 1); // Fill the color. for (var i = 0; i < 6; i++) colors[offs + i] = c; // Make each face. vertices[offs++] = v1; vertices[offs++] = v2; vertices[offs++] = v3; vertices[offs++] = v3; vertices[offs++] = v2; vertices[offs++] = v1; } // Index array. Simply enumerates the vertices. var indices = new int[vertices.Length]; for (var i = 0; i < indices.Length; i++) indices[i] = i; // Build a mesh. _mesh = new Mesh(); _mesh.hideFlags = HideFlags.DontSave; _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10); _mesh.vertices = vertices; _mesh.colors = colors; _mesh.SetIndices(indices, MeshTopology.Triangles, 0); _mesh.RecalculateNormals(); _subdivided = _subdivision; }