- Home /
Applying a texture to a mesh created at runtime
I have a mesh object whose vertices and triangles are calculated at runtime. The mesh has a material applied in the inspector which uses this standard URP shader from unity.
When I run the code in editor, the mesh has the correct geometry, but it appears as all one color. As I adjust the texture offset in the material, I see the entire mesh flick to a different color - it's as though only a single point on the texture is being sampled.
I have also tested with a standard plane created from the menu with the same material applied. The texture renders correctly in this case, so the material/shader appears to be doing the right thing.
Here is where I create the mesh (taken from a tutorial I was following but am now starting to deviate from):
void Awake()
{
GetComponent<MeshFilter>().mesh = hexMesh = new Mesh();
meshCollider = gameObject.AddComponent<MeshCollider>();
hexMesh.name = "Hex Mesh";
vertices = new List<Vector3>();
triangles = new List<int>();
}
public void Triangulate(HexCell[] cells)
{
hexMesh.Clear();
vertices.Clear();
triangles.Clear();
for (int i = 0; i < cells.Length; i++)
{
Triangulate(cells[i]);
}
hexMesh.vertices = vertices.ToArray();
hexMesh.triangles = triangles.ToArray();
hexMesh.RecalculateBounds();
hexMesh.RecalculateTangents();
hexMesh.RecalculateNormals();
meshCollider.sharedMesh = hexMesh;
}
void Triangulate(HexCell cell)
{
Vector3 center = cell.transform.localPosition;
for(int i =0; i < 6; i++)
{
AddTriangle(
center,
center + HexMetrics.corners[i],
center + HexMetrics.corners[i+1]
);
}
}
void AddTriangle(Vector3 v1, Vector3 v2, Vector3 v3)
{
int vertexIndex = vertices.Count;
vertices.Add(v1);
vertices.Add(v2);
vertices.Add(v3);
triangles.Add(vertexIndex);
triangles.Add(vertexIndex + 1);
triangles.Add(vertexIndex + 2);
}
Any suggestions on what I am doing wrong?
I don't see any mention of uv mapping in your script. Without uv mapping applied to your mesh, all texture coordinates would effectively be (0, 0).