Created
January 20, 2021 08:22
-
-
Save ChrisPritchard/91b0923df8c3c0fcccfc56095b7d3119 to your computer and use it in GitHub Desktop.
Core file from this excellent Unity tutorial: https://catlikecoding.com/unity/tutorials/procedural-grid/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // from this tutorial: https://catlikecoding.com/unity/tutorials/procedural-grid/ | |
| // attach to a gameobject | |
| // for the mesh renderer, create a material with a texture as an albedo and/or a texture for a normal map | |
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] | |
| public class Grid : MonoBehaviour | |
| { | |
| public int XSize, YSize; | |
| Vector3[] vertices; | |
| Vector2[] uv; | |
| Vector4[] tangents; | |
| int[] triangles; | |
| void Start() | |
| { | |
| //StartCoroutine(Generate()); | |
| Generate(); | |
| } | |
| private void Generate() | |
| { | |
| //var wait = new WaitForSeconds(0.05f); | |
| vertices = new Vector3[(XSize+1)*(YSize+1)]; | |
| uv = new Vector2[vertices.Length]; | |
| tangents = new Vector4[vertices.Length]; | |
| triangles = new int[XSize*YSize*6]; | |
| var tangent = new Vector4(1f,0f,0f,-1f); | |
| for (var y = 0; y <= YSize; y++) | |
| for (var x = 0; x <= XSize; x++) | |
| { | |
| var index = y * (XSize + 1) + x; | |
| vertices[index] = new Vector2(x, y); | |
| uv[index] = new Vector2((float)x / XSize, (float)y / YSize); | |
| tangents[index] = tangent; | |
| if (y == YSize || x == XSize) | |
| continue; | |
| var i = (y*XSize+x)*6; | |
| triangles[i] = index; | |
| triangles[i+1] = index+XSize+1; | |
| triangles[i+2] = index+1; | |
| triangles[i+3] = index+XSize+1; | |
| triangles[i+4] = index+XSize+2; | |
| triangles[i+5] = index+1; | |
| //yield return wait; | |
| } | |
| var meshFilter = GetComponent<MeshFilter>(); | |
| meshFilter.mesh = new Mesh | |
| { | |
| name = "Procedural Grid", | |
| vertices = vertices, | |
| uv = uv, | |
| tangents = tangents, | |
| triangles = triangles | |
| }; | |
| meshFilter.mesh.RecalculateNormals(); | |
| } | |
| private void OnDrawGizmos() | |
| { | |
| if (vertices == null) | |
| return; | |
| Gizmos.color = Color.black; | |
| foreach(var vertex in vertices) | |
| Gizmos.DrawSphere(vertex, 0.1f); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment