Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5.  
  6. [RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))]
  7. public class Grid : MonoBehaviour
  8. {
  9. public int xScale;
  10. public int yScale;
  11. private Mesh mesh;
  12.  
  13. private Vector3[] vertexBuffer;
  14.  
  15. private void Awake()
  16. {
  17. StartCoroutine(Generator());
  18. }
  19.  
  20. private IEnumerator Generator()
  21. {
  22. WaitForSeconds wait = new WaitForSeconds(0.05f);
  23. vertexBuffer = new Vector3[(xScale + 1) * (yScale + 1)];
  24. Vector2[] uv = new Vector2[vertexBuffer.Length];
  25. GetComponent<MeshFilter>().mesh = mesh = new Mesh();
  26.  
  27. for (int i = 0, z = 0; z <= yScale; z++)
  28. {
  29. for (int x = 0; x <= xScale; x++, i++)
  30. {
  31. vertexBuffer[i] = new Vector3(x, Random.Range(0.0f,1.0f), z);
  32. uv[i] = new Vector2((float)x / (float)xScale, (float)z / (float)yScale);
  33. yield return wait;
  34. }
  35. }
  36.  
  37. mesh.vertices = vertexBuffer;
  38. mesh.uv = uv;
  39.  
  40. int[] tris = new int[xScale * yScale * 6];
  41.  
  42. for (int ti = 0, vi = 0, y = 0; y < yScale; y++, vi++)
  43. {
  44. for (int x = 0; x < xScale; x++, ti += 6, vi++)
  45. {
  46. tris[ti] = vi;
  47. tris[ti + 1] = tris[ti + 4] = vi + xScale + 1;
  48. tris[ti + 2] = tris[ti + 3] = vi + 1;
  49. tris[ti + 5] = vi + xScale + 2;
  50. }
  51. }
  52.  
  53. mesh.triangles = tris;
  54. mesh.RecalculateNormals();
  55. }
  56.  
  57. private void OnDrawGizmos()
  58. {
  59. if (vertexBuffer == null)
  60. {
  61. return;
  62. }
  63.  
  64. Gizmos.color = Color.black;
  65. for (int i = 0; i< vertexBuffer.Length;i++)
  66. {
  67. Gizmos.DrawSphere(vertexBuffer[i], 0.1f);
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement