Skip to content

Instantly share code, notes, and snippets.

@Q-Bert-Reynolds
Last active June 2, 2017 16:05
Show Gist options
  • Save Q-Bert-Reynolds/a9466aeae3b78462c3f08bebc0782810 to your computer and use it in GitHub Desktop.
Save Q-Bert-Reynolds/a9466aeae3b78462c3f08bebc0782810 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class Plane : MonoBehaviour {
[Range(2,100)]public int width = 10;
[Range(2,100)]public int length = 10;
[ContextMenu("Setup Mesh")]
void SetupMesh () {
int size = width * length;
Vector3[] verts = new Vector3[size];
Vector2[] uvs = new Vector2[size];
Color[] colors = new Color[size];
List<int> tris = new List<int>();
for (int x = 0; x < width; x++) {
for (int z = 0; z < length; z++) {
int index = x + z * width;
verts[index] = new Vector3(x, 0, z);
uvs[index] = new Vector2(
(float)x / (float)width,
(float)z / (float)length
);
colors[index] = Color.white;
if (x < width-1 && z < length-1) {
int above = x + (z+1) * width;
tris.AddRange(new int[] {
index, above , above + 1,
index, above + 1, index + 1,
});
}
}
}
Mesh mesh = new Mesh();
mesh.name = "Plane";
mesh.vertices = verts;
mesh.uv = uvs;
mesh.colors = colors;
mesh.triangles = tris.ToArray();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
MeshFilter meshFilter = GetComponent<MeshFilter>();
meshFilter.sharedMesh = mesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment