I’m trying to make a grid using GL but It is only visible in the Scene and not the Game view.
Is it Unity Pro only.
I read in a comment that it could be used if you have Unity 4.0+
If it is pro only, any other suggestions on how to make a grid would be helpful. I already tried LineRenderer and it didn’t perform well.
Code in question:
void OnPostRender(){
MakeGrid();
}
void OnDrawGizmos(){
MakeGrid();
}
public void MakeGrid(){
mat.SetPass(0);
GL.PushMatrix();
GL.Begin(GL.LINES);
GL.Color(Color.white);
int direction = -1;
int x1;
int x2;
for(int z=size_z-1; z>=0; z--){
if (direction>0){
x1 = 0;
x2 = size_x-1;
}else{
x1 = size_x-1;
x2 = 0;
}
GL.Vertex(nodes[x1,z].unityPosition);
GL.Vertex(nodes[x2,z].unityPosition);
direction *= -1;
}
GL.End();
GL.PopMatrix();
}
The GL class is available only to Unity Pro. If you want to make a grid, that is some decisions. The first, of course, is LineRenderer. The second, use Projector (it is possible to find in standard Assets Unity - the grid, one of three prefabs). The third way, use Vectrocity plugin.
The easiest way to make a grid is using a mesh with it’s topology set to Lines. Note that the MeshTopology enum wasn’t introduced til after 4.0 sometime.
/**
* Renders a grid at 0,0,0.
*/
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class Grid : MonoBehaviour
{
public int lines = 10; ///< Default to 10x10 grid
public float scale = 1f; ///< 1m * scale
public Material gridMaterial; ///< Should have a color component
public Color gridColor = new Color(.5f, .5f, .5f, .6f);
void Start()
{
GetComponent<MeshFilter>().sharedMesh = GridMesh(lines, scale);
GetComponent<MeshRenderer>().sharedMaterial = gridMaterial;
GetComponent<MeshRenderer>().sharedMaterial.color = gridColor;
}
/**
* Builds a grid object in 2d space
*/
Mesh GridMesh(int lineCount, float scale)
{
float half = (lineCount/2f) * scale;
lineCount++; // to make grid lines equal and such
Vector3[] lines = new Vector3[lineCount * 4]; // 2 vertices per line, 2 * lines per grid
int[] indices = new int[lineCount * 4];
int n = 0;
for(int y = 0; y < lineCount; y++)
{
indices[n] = n;
lines[n++] = new Vector3( y * scale - half, 0f, -half );
indices[n] = n;
lines[n++] = new Vector3( y * scale - half, 0f, half );
indices[n] = n;
lines[n++] = new Vector3( -half, 0f, y * scale - half );
indices[n] = n;
lines[n++] = new Vector3( half, 0f, y * scale - half );
}
Mesh tm = new Mesh();
tm.vertices = lines;
tm.subMeshCount = 1;
tm.SetIndices(indices, MeshTopology.Lines, 0);
tm.uv = new Vector2[lines.Length];
return tm;
}
}