MeshIndexToUV.cs
1 using UnityEngine; 2 3 [RequireComponent(typeof(MeshFilter))] 4 public class MeshIndexToUV : MonoBehaviour 5 { 6 [ContextMenu("Apply Vertex Indices To UVs")] 7 void ApplyIndices() 8 { 9 MeshFilter mf = GetComponent<MeshFilter>(); 10 Mesh mesh = mf.sharedMesh; 11 12 if (mesh == null) 13 { 14 Debug.LogError("No mesh found on MeshFilter!"); 15 return; 16 } 17 18 int vertexCount = mesh.vertexCount; 19 Vector2[] uvs = new Vector2[vertexCount]; 20 21 for (int i = 0; i < vertexCount; i++) 22 { 23 // Store the vertex index in UV.x 24 uvs[i] = new Vector2(i, 0); 25 } 26 Mesh meshCopy = Instantiate(mesh); 27 meshCopy.SetUVs(2, new System.Collections.Generic.List<Vector2>(uvs)); 28 // Optional: rename so it’s clear this is a copy 29 meshCopy.name = mesh.name + "_Copy"; 30 31 // Assign back so we are not editing the original 32 mf.mesh = meshCopy; 33 } 34 35 [ContextMenu("Create and Bind Texture Attributes")] 36 void CreateAndBindTextureAttributes() 37 { 38 MeshFilter mf = GetComponent<MeshFilter>(); 39 Mesh mesh = mf.sharedMesh; 40 41 var material = GetComponent<Renderer>().sharedMaterial; 42 43 int vertexCount = mesh.vertexCount; 44 Texture2D attributeTex = new Texture2D(vertexCount, 1, TextureFormat.RGBAFloat, false, true); 45 attributeTex.filterMode = FilterMode.Point; 46 47 // Fill it with your data 48 Color[] data = new Color[vertexCount]; 49 for (int i = 0; i < vertexCount; i++) { 50 Vector3 velocity; 51 velocity.x = (i%3 == 0)?1:0; 52 velocity.y = (i%3 == 1)?1:0; 53 velocity.z = (i%3 == 2)?1:0; 54 data[i] = new Color(velocity.x, velocity.y, velocity.z, 1); 55 // data[i] = new Color(0, 0, 0, 1); 56 } 57 58 ComputeBuffer buffer = new ComputeBuffer(vertexCount, sizeof(float) * 4); 59 buffer.SetData(data); 60 material.SetBuffer("_AttrBuffer", buffer); 61 material.SetInt("_VertexCount", mesh.vertexCount); 62 } 63 }