Skip to content

Instantly share code, notes, and snippets.

@davepape davepape/grid.cs
Created Oct 17, 2018

What would you like to do?
Create a Unity mesh containing a simple 2D grid of triangles
// Create a mesh of triangles in a 2D grid
// Attach this script to a GameObject that already has a MeshFilter - it will use that MeshFilter, replacing its existing mesh data
// Creates a numCols x numRows grid of vertices in the X/Y plane. Then for each square cell in the grid it creates 2 triangles
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grid : MonoBehaviour {
public int numRows=10, numCols=10;
public float minX=-1, maxX=1, minY=-1, maxY=1;
void Start ()
int index;
Vector3[] myVerts = new Vector3[numRows*numCols];
index = 0;
for (int j=0; j < numRows; j++)
for (int i=0; i < numCols; i++)
float x = Mathf.Lerp(minX,maxX,i/(numCols-1f));
float y = Mathf.Lerp(minY,maxY,j/(numRows-1f));
myVerts[index] = new Vector3(x,y,0);
int[] myTris = new int[(numRows-1)*(numCols-1)*2*3];
index = 0;
for (int j=0; j < numRows-1; j++)
for (int i=0; i < numCols-1; i++)
myTris[index++] = i + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
myMesh.vertices = myVerts;
myMesh.triangles = myTris;
void Update ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.