Пример #1
0
    static void CombineChildMeshes(MenuCommand cmd)
    {
        MeshFilter mf          = cmd.context as MeshFilter;
        var        mesh        = mf.sharedMesh;
        var        meshFilters = mf.GetComponentsInChildren <MeshFilter>().Where(i => i != mf).ToArray();
        // var transform = mf.GetComponent<Transform>();

        var tile = mf.GetComponent <Tile>();

        var combine = new CombineInstance[meshFilters.Length];

        for (int i = 0; i < meshFilters.Length; i++)
        {
            var c = meshFilters[i];
            Debug.Log(c.gameObject.name);
            var m = c.GetComponent <MeshFilter>().sharedMesh;
            var t = c.GetComponent <Transform>();

            var x  = i % tile.rect.width;
            var y  = i / tile.rect.width;
            var uv = new Vector2((float)x / tile.rect.width, (float)y / tile.rect.height);
            m.uv = new Vector2[] { uv, uv, uv };

            combine[i].mesh = m;
            //https://answers.unity.com/questions/231249/instanced-meshes-are-being-offset-to-weird-positio.html
            combine[i].transform = Matrix4x4.TRS(t.localPosition, t.localRotation, t.localScale);
        }

        mesh.colors = Enumerable.Range(0, mesh.triangles.Length / 3)
                      .SelectMany(i =>
        {
            return(new Color[] {
                Color.red,
                Color.green,
                Color.blue
            });
        })
                      .ToArray();

        mesh.CombineMeshes(combine, true, true, false);
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mf.GetComponent <MeshRenderer>().enabled = true;

        for (int i = 0; i < meshFilters.Length; i++)
        {
            UnityEngine.Object.DestroyImmediate(meshFilters[i].gameObject);
        }
    }