• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by trevk84 · Dec 30, 2017 at 04:41 AM · combinemeshes

Combine meshes with submeshes help

I tried, but I couldn't figure it out. Google and Answers got me close, but I need help. I'm trying to combine multiple instanced meshes, each having two submeshes. The following code creates multiple game objects, one for each submesh in the instance. For example, I'm trying to combine a group of 10 trees, each tree having a trunk material and a leaf material. The result of the code leaves me with two gameobjects, one of all the trunks combined, and one of all the leaves combined. I would like to end up with one gameobject, of all the trunks and leaves combined, and the two materials.

 void Start()
     {
         //create an empty gameobject, add this script to it
         //attach multiple gameobject clones to this gameobject (all having the same mesh and multiple materials)
         //run program
         if (gameObject.transform.childCount > 1)
         {
             //line up placement of children around empty parent
             float width = gameObject.transform.GetChild(0).GetComponent<MeshFilter>().mesh.bounds.size.x;
             for (int i = 0; i < gameObject.transform.childCount; i++)
             {
                 gameObject.transform.GetChild(i).transform.localPosition = new Vector3(i * width - (width * gameObject.transform.childCount / 2f), 0, 0);
                 gameObject.transform.GetChild(i).transform.localEulerAngles = new Vector3(Random.Range(-5f, 5f), Random.Range(0, 360), Random.Range(-5f, 5f));
             }
 
             //get materials from first child (every child is the same)
             Material[] material = gameObject.transform.GetChild(0).GetComponent<MeshRenderer>().materials;
 
             CombineInstance ci;
             MeshFilter[] meshFilters = gameObject.GetComponentsInChildren<MeshFilter>();
             List<CombineInstance> combine = new List<CombineInstance>();
             GameObject[] parent = new GameObject[meshFilters[0].sharedMesh.subMeshCount];
             for (int i = 0; i < parent.Length; i++)
             {
                 parent[i] = new GameObject();
                 parent[i].name = "Submesh " + i;
 
                 for (int ii = 0; ii < meshFilters.Length; ii++)
                 {
                     if (meshFilters[i].sharedMesh != null)
                     {
                         ci = new CombineInstance();
                         ci.mesh = meshFilters[ii].sharedMesh;
                         ci.subMeshIndex = i;
                         ci.transform = meshFilters[ii].transform.localToWorldMatrix;
                         combine.Add(ci);
                     }
                     else
                     {
                         ci = new CombineInstance();
                         ci.mesh = new Mesh();
                         combine.Add(ci);
                     }
                 }
 
                 parent[i].AddComponent<MeshFilter>().mesh.CombineMeshes(combine.ToArray());
                 parent[i].AddComponent<MeshRenderer>().material = material[i];
             }
 
             //destroy all of original gameobjects; they are no longer needed.
             for (int ii = 0; ii < gameObject.transform.childCount; ii++)
             {
                 Destroy(gameObject.transform.GetChild(ii).gameObject);
             }
 
             //attatch newly created gameobjects to main gameobject to keep things clean
             for (int i = 0; i < parent.Length; i++)
             {
                 parent[i].transform.parent = gameObject.transform;
             }
         }
         else
         {
             Debug.Log("NOT ENOUGH CHILDREN TO COMBINE");
         }
     }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by trevk84 · Dec 30, 2017 at 09:56 PM

Got it:

     public GameObject obj;
     [Range(0, 100)]
     public int amount;
 
     // Use this for initialization
     void Start ()
     {
         Duplicate();
     }
     
     private void Duplicate()
     {
         Mesh mainMesh = obj.GetComponent<MeshFilter>().sharedMesh;
 
         Mesh meshToCopy = new Mesh();
         meshToCopy.vertices = mainMesh.vertices;
         meshToCopy.triangles = mainMesh.triangles;
         meshToCopy.normals = mainMesh.normals;
         meshToCopy.uv = mainMesh.uv;
 
         Matrix4x4[] matrix = new Matrix4x4[amount];
         for (int i = 0; i < amount; i++)
         {
             matrix[i].SetTRS(new Vector3(i * 10, 0, 0), Quaternion.Euler(new Vector3(Random.Range(-5, 5), Random.Range(0, 360), Random.Range(-5, 5))), Vector3.one);
         }
 
         CombineInstance[] ci = new CombineInstance[amount];
         for (int i = 0; i < amount; i++)
         {
             ci[i] = new CombineInstance();
             ci[i].mesh = meshToCopy;
             ci[i].transform = matrix[i];
         }
 
         Material[] materials = obj.GetComponent<MeshRenderer>().sharedMaterials;
 
         Mesh batchedMesh = gameObject.AddComponent<MeshFilter>().mesh = new Mesh();
         batchedMesh.CombineMeshes(ci);
         gameObject.AddComponent<MeshRenderer>().materials = materials;
         
         int[] mainSubTri;
         int[] newSubTri;
         batchedMesh.subMeshCount = mainMesh.subMeshCount;
 
         for (int i = 0; i < mainMesh.subMeshCount; i++)
         {
             mainSubTri = mainMesh.GetTriangles(i);
 
             newSubTri = new int[mainSubTri.Length * amount];
 
             for (int ii = 0; ii < amount; ii++)
             {
                 for (int iii = 0; iii < mainSubTri.Length; iii++)
                 {
                     newSubTri[(ii * mainSubTri.Length) + iii] = mainSubTri[iii] + (ii * mainMesh.vertexCount);
                 }
             }
             batchedMesh.SetTriangles(newSubTri, i);
         }
     }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

71 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Why mesh colliders doesn't work with combined meshes using Mesh.CombineMeshes? 3 Answers

Combining Objects for Performance 0 Answers

500K upper bound on total number of meshes? 0 Answers

Lightmapping Error with combined meshes 0 Answers

Is there a maximum amount of memory Unity assigns for instantiating meshes? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges