- Home /
How to tile textures on a procedural mesh?
I have the following code that creates a mesh and works very well. I want to apply a tiled texture system to allow each quad (2 triangles) to be able to have texture applied to it. My source for the textures is an image that consists of 100 textures (in a 10x10 grid of 32x32 textures). I have only a vert basic understanding of meshes. I am sure I am just lacking the knowledge of what to change here to make it possible so any help is greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShopFloor : MonoBehaviour {
public int floorWidth;
public int floorHeight;
Mesh mesh;
Vector3[] vertices;
int[] triangles;
Vector2[] uvs;
void Start() {
mesh = GetComponent<MeshFilter>().mesh;
GenerateFloor();
UpdateFloor();
}
void GenerateFloor() {
vertices = new Vector3[(floorWidth + 1) * (floorHeight + 1)];
for(int i = 0, z = 0; z <= floorHeight; z++) {
for(int x = 0; x <= floorWidth; x++) {
float y = Mathf.PerlinNoise(x * 0.3f,z * 0.3f) * 2.0f;
vertices[i] = new Vector3(x,y,z);
i++;
}
}
triangles = new int[floorWidth * floorHeight * 6];
int vert = 0;
int tris = 0;
for(int z = 0; z < floorHeight; z++) {
for(int x = 0; x < floorWidth; x++) {
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + floorWidth + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + floorWidth + 1;
triangles[tris + 5] = vert + floorWidth + 2;
vert++;
tris += 6;
}
vert++;
}
uvs = new Vector2[vertices.Length];
for(int i = 0, z = 0; z <= floorHeight; z++) {
for(int x = 0; x <= floorWidth; x++) {
uvs[i] = new Vector2((float)x / floorWidth,(float)z / floorHeight);
i++;
}
}
}
void UpdateFloor() {
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals();
}
void OnDrawGizmos() {
if(vertices == null) {
return;
}
for(int i = 0; i < vertices.Length; i++) {
Gizmos.DrawSphere(vertices[i],0.05f);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Procedural mesh generation, problem with textures 1 Answer
multiple textures on one mesh + different Albedos 1 Answer
Texture vs. Material 0 Answers
Get texture with UV Mesh Mapping 0 Answers
vrchat model issue - Flashing red and yellow lights 0 Answers