Search Unity

Dynamic Mesh Filter and Mesh Renderer: useful or not?

Discussion in 'World Building' started by jeancallisti, Feb 12, 2019.

  1. jeancallisti

    jeancallisti

    Joined:
    Oct 27, 2017
    Posts:
    9
    I'm procedurally creating a very large object -- let's say a terrain. The data is divided into subspaces -- let's say chunks. The mesh complexity depends on the distance, and my logic knows how to generate less triangles for parts far away. Then my logic passes the data to one mesh filter.

    My question is about something else : Is it better to have:
    • several Mesh Renderer and Mesh Filter instances, each of them being in charge of a subspace of the overall data structure (let's say -- one Mesh Renderer + one Mesh filter per chunk),
    • OR is it better to have one pair of Mesh Filter + Mesh Renderer for the entire terrain?

    I'm asking because I don't see topics on how to dynamically instantiate Mesh Renderers and Mesh Filters. In 99% of the forums' threads, people have procedurally-generated objects, but those are apparently manually created in the Editor, along with their Mesh Filter and Mesh Renderer. Only the mesh ever seems to be generated dynamically and passed to the Mesh Filter.



    Is it a thing to dynamically instantiate Mesh Filters and Mesh Renderers?
     
    Last edited: Feb 13, 2019
  2. jeancallisti

    jeancallisti

    Joined:
    Oct 27, 2017
    Posts:
    9
    OK found it :

    Code (CSharp):
    1.          GameObject myObject = new GameObject("myObject");
    2.          myObject.AddComponent<MeshFilter>();
    3.          myObject.AddComponent<MeshRenderer>();
    4.          myObject.GetComponent<MeshFilter>().mesh = new Mesh();
    5.          // Load a material named "TerrainMat" from a folder named "Resources"
    6.          Material terrainMat = Resources.Load<Material>("TerrainMat");
    7.          myObject.GetComponent<Renderer>().material = terrainMat;