Tanoda
pb_Grid.cs
Go to the documentation of this file.
1
5using UnityEngine;
6using System.Collections;
7
8namespace GILES
9{
10 [RequireComponent(typeof(MeshFilter))]
11 [RequireComponent(typeof(MeshRenderer))]
12 public class pb_Grid : MonoBehaviour
13 {
14 [Tooltip("This script generates a grid mesh on load.")]
15
16 // Default to 10x10 grid
17 public int lines = 10;
18
19 // 1m * scale
20 public float scale = 1f;
21 public Color gridColor = new Color(.5f, .5f, .5f, .6f);
22 public Material gridMaterial;
23
24 void Start()
25 {
26 GetComponent<MeshFilter>().sharedMesh = GridMesh(lines, scale);
27 GetComponent<MeshRenderer>().sharedMaterial = gridMaterial;
28 GetComponent<MeshRenderer>().sharedMaterial.color = gridColor;
29
30 transform.position = Vector3.zero;
31 }
32
36 Mesh GridMesh(int lineCount, float scale)
37 {
38 float half = (lineCount/2f) * scale;
39
40 lineCount++; // to make grid lines equal and such
41
42 Vector3[] lines = new Vector3[lineCount * 4]; // 2 vertices per line, 2 * lines per grid
43 Vector3[] normals = new Vector3[lineCount * 4];
44 Vector2[] uv = new Vector2[lineCount * 4];
45 int[] indices = new int[lineCount * 4];
46
47 int n = 0;
48 for(int y = 0; y < lineCount; y++)
49 {
50 indices[n] = n;
51 uv[n] = y % 10 == 0 ? Vector2.one : Vector2.zero;
52 lines[n++] = new Vector3( y * scale - half, 0f, -half );
53
54 indices[n] = n;
55 uv[n] = y % 10 == 0 ? Vector2.one : Vector2.zero;
56 lines[n++] = new Vector3( y * scale - half, 0f, half );
57
58 indices[n] = n;
59 uv[n] = y % 10 == 0 ? Vector2.one : Vector2.zero;
60 lines[n++] = new Vector3( -half, 0f, y * scale - half );
61
62 indices[n] = n;
63 uv[n] = y % 10 == 0 ? Vector2.one : Vector2.zero;
64 lines[n++] = new Vector3( half, 0f, y * scale - half );
65 }
66
67 for(int i = 0; i < lines.Length; i++)
68 {
69 normals[i] = Vector3.up;
70 }
71
72 Mesh tm = new Mesh();
73
74 tm.name = "GridMesh";
75 tm.vertices = lines;
76 tm.normals = normals;
77 tm.subMeshCount = 1;
78 tm.SetIndices(indices, MeshTopology.Lines, 0);
79 tm.uv = uv;
80
81 return tm;
82 }
83 }
84}
UnityEngine.Color Color
Definition: TestScript.cs:32
float scale
Definition: pb_Grid.cs:20
Color gridColor
Definition: pb_Grid.cs:21
Material gridMaterial
Definition: pb_Grid.cs:22