Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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);
- index++;
- }
- 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.Clear();
- myMesh.vertices = myVerts;
- myMesh.triangles = myTris;
- myMesh.RecalculateNormals();
- }
- void Update ()
- {
- }
- }
Add Comment
Please, Sign In to add comment