- Home /
Apply texture to dynamic mesh
In my Start or init methods I create my mesh like so
Mesh mesh = new Mesh();
mesh.vertices = aVertices;
mesh.uv = aUV;
mesh.triangles = aTriangles;
mesh.RecalculateNormals();
and then in my Update method I have
mesh.vertices = aVertices;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
in both cases aVertices, aUV and aTriangles are previously defined and contain correct data.
My question is, how do I then apply a material or texture to this dynamic mesh, say from a bitmap in my Resources folder?
Answer by Glurth · Feb 18, 2016 at 04:21 PM
Assuming you are using the MeshRenderer Component to draw the mesh:
Convert the bmp to a png and store this file in your project's unity assets folder
Create a new Material in Unity. This will start with the standard shader.
In the stanadard shader options for the material, click the "circle-dot" next to "albedo", and select the .png file you copied earlier.
Now you have the material you need configured in unity(rename it), go back to the mesh object, and it's MeshRenderer component, select the new material you created. This last step applies for ANY materials you apply to your dynamic meshes and can be easily scripted. (I would recommend AGAINST scripting the previous steps, do them manually and just reference that material in your scripts)
That should be it.
Here it one complication to be aware of: submeshes- each submesh of a mesh (see Mesh.GetTrinagles(int)) can have it's OWN material in the MeshRenderer, which actually stores an ARRAY of materials. (in scripting, you are accessing the first material in the array when using MeshRenderer.material, and the array itself when using MehRenderer.materials)
Your answer
Follow this Question
Related Questions
Change material of dynamically generated mesh 1 Answer
Assigning UV Map to model at runtime 0 Answers
How can i achieve texturing of a dynamic generated Hex? 0 Answers
loading texture from folder dynamically? 2 Answers
Movie GUI Texture Alpha? 1 Answer