[ad_1]
I created a script that allows me to change my meshes configuration while the app is running. I don’t know meshes all that well and am running into issues with texturing. How do I need to set my uv’s so that my texture shows correctly? There’s likely other issues too so please bear with me.
custom 10×10 mesh is on the left, standard plane right
script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpMesh : MonoBehaviour
{
public int width = 1;
public int height = 1;
private Vector2 _lastSize = Vector2.zero;
private Mesh mesh;
private void Start() {
_lastSize.x = width;
_lastSize.y = height;
}
void OnValidate() {
if(Application.isPlaying != true) return;
if(width == _lastSize.x && height == _lastSize.y) return;
MakeMesh();
}
void MakeMesh() {
mesh = GetComponent<MeshFilter> ().mesh;
Vector3[] vertices = new Vector3[4 * width * height];
Vector4[] tangents = new Vector4[4 * width * height];
Vector2[] uv = new Vector2[4 * width * height];
int[] triangles = new int[6 * width * height];
var uvH = 1f / height;
var uvW = 1f / width;
for(int col = 0; col < width; ++col) {
for(int row = 0; row < height; ++row) {
int index = row * width + col;
float x = transform.position.x - width/2;
float y = transform.position.y;
float z = transform.position.z + height/2;
vertices[index*4 + 0] = new(x + col, y, z - row);
vertices[index*4 + 1] = new(x + col+1, y, z - row);
vertices[index*4 + 2] = new(x + col+1, y, z - row-1);
vertices[index*4 + 3] = new(x + col, y, z - row-1);
tangents[index*4 + 0] = new(1f, 0f, 0f, -1f);
tangents[index*4 + 1] = new(1f, 0f, 0f, -1f);
tangents[index*4 + 2] = new(1f, 0f, 0f, -1f);
tangents[index*4 + 3] = new(1f, 0f, 0f, -1f);
uv[index*4 + 0] = new(col + col*uvW + uvW, row + row*uvH);
uv[index*4 + 1] = new(col + col*uvW, row + row*uvH);
uv[index*4 + 2] = new(col + col*uvW, row + row*uvH + uvH);
uv[index*4 + 3] = new(col + col*uvW + uvW, row + row*uvH + uvH);
triangles[index*6 + 0] = index*4 + 0;
triangles[index*6 + 1] = index*4 + 1;
triangles[index*6 + 2] = index*4 + 2;
triangles[index*6 + 3] = index*4 + 0;
triangles[index*6 + 4] = index*4 + 2;
triangles[index*6 + 5] = index*4 + 3;
}
}
mesh.Clear ();
mesh.vertices = vertices;
mesh.tangents = tangents;
mesh.triangles = triangles;
mesh.uv = uv;
// mesh.Optimize ();
// mesh.RecalculateNormals ();
Debug.Log($"MAKE {height}x{width} v{vertices.Length} t{triangles.Length}");
}
}
texture
[ad_2]