- Home /
Draw grid lines in game view?
What is the best way to show grid lines in game view.. I want to show grid to the user in my game.. I was wondering what is the most convenient way?
Since I have mouse selection on many objects, I do not want that the grid cause any problem with the selection..
You could try a custom shader on your objects. I am not sure if there is a way to show the scene grid. You may have to manually create one.
I'm looking for a way to generate this grid at a specific point.
I'd like to know If I can specify where this grid is generated. I would like this grid to move with the camera. So I would like to generate the grid in a position specified by a child gameobject of the camera.
So when the camera moves the grid moves relative to the camera.
Any Ideas?
Any help would be greatly appreciated.
Look at the three properties startX, startY, startZ. They specify the origin of the grid. You should be able to tie these values to the transform.position of some other game object by adding a reference to it.
Hello guys,
How do I make this grid draw behind my game objects? Currently, they are drawn over my game elements.
Thanks!
Answer by Em3rgency · Jun 27, 2013 at 02:00 PM
2017-06-17 EDIT: Guys, this is now wayyyyy out of date. Many people report it not working anymore. Try to look through the later dated answers for any possible fixes, otherwise I know this code no longer works as is. Its your turn to develop a better one ;)
This will probably be a bit overkill to what you want, but I'm too lazy to edit it.
What you have here is code for a 3 dimensional double grid with editable total size, start position and grid step size. If you leave the Y size at 0, you will have a 2D grid. Additionally, numpad +/- lets you move it up and down. Attach this script to your camera.
(It also takes a plane object, because I needed collision for it, but you can comment out the 3 lines to do with the plane altogether with no loss of functionality).
using UnityEngine;
using System.Collections;
public class gridOverlay : MonoBehaviour {
public GameObject plane;
public bool showMain = true;
public bool showSub = false;
public int gridSizeX;
public int gridSizeY;
public int gridSizeZ;
public float smallStep;
public float largeStep;
public float startX;
public float startY;
public float startZ;
private float offsetY = 0;
private float scrollRate = 0.1f;
private float lastScroll = 0f;
private Material lineMaterial;
private Color mainColor = new Color(0f,1f,0f,1f);
private Color subColor = new Color(0f,0.5f,0f,1f);
void Start ()
{
}
void Update ()
{
if(lastScroll + scrollRate < Time.time)
{
if(Input.GetKey(KeyCode.KeypadPlus))
{
plane.transform.position = new Vector3(plane.transform.position.x, plane.transform.position.y + smallStep, plane.transform.position.z);
offsetY += smallStep;
lastScroll = Time.time;
}
if(Input.GetKey(KeyCode.KeypadMinus))
{
plane.transform.position = new Vector3(plane.transform.position.x, plane.transform.position.y - smallStep, plane.transform.position.z);
offsetY -= smallStep;
lastScroll = Time.time;
}
}
}
void CreateLineMaterial()
{
if( !lineMaterial ) {
lineMaterial = new Material( "Shader \"Lines/Colored Blended\" {" +
"SubShader { Pass { " +
" Blend SrcAlpha OneMinusSrcAlpha " +
" ZWrite Off Cull Off Fog { Mode Off } " +
" BindChannels {" +
" Bind \"vertex\", vertex Bind \"color\", color }" +
"} } }" );
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;}
}
void OnPostRender()
{
CreateLineMaterial();
// set the current material
lineMaterial.SetPass( 0 );
GL.Begin( GL.LINES );
if(showSub)
{
GL.Color(subColor);
//Layers
for(float j = 0; j <= gridSizeY; j += smallStep)
{
//X axis lines
for(float i = 0; i <= gridSizeZ; i += smallStep)
{
GL.Vertex3( startX, j + offsetY, startZ + i);
GL.Vertex3( gridSizeX, j + offsetY, startZ + i);
}
//Z axis lines
for(float i = 0; i <= gridSizeX; i += smallStep)
{
GL.Vertex3( startX + i, j + offsetY, startZ);
GL.Vertex3( startX + i, j + offsetY, gridSizeZ);
}
}
//Y axis lines
for(float i = 0; i <= gridSizeZ; i += smallStep)
{
for(float k = 0; k <= gridSizeX; k += smallStep)
{
GL.Vertex3( startX + k, startY + offsetY, startZ + i);
GL.Vertex3( startX + k, gridSizeY + offsetY, startZ + i);
}
}
}
if(showMain)
{
GL.Color(mainColor);
//Layers
for(float j = 0; j <= gridSizeY; j += largeStep)
{
//X axis lines
for(float i = 0; i <= gridSizeZ; i += largeStep)
{
GL.Vertex3( startX, j + offsetY, startZ + i);
GL.Vertex3( gridSizeX, j + offsetY, startZ + i);
}
//Z axis lines
for(float i = 0; i <= gridSizeX; i += largeStep)
{
GL.Vertex3( startX + i, j + offsetY, startZ);
GL.Vertex3( startX + i, j + offsetY, gridSizeZ);
}
}
//Y axis lines
for(float i = 0; i <= gridSizeZ; i += largeStep)
{
for(float k = 0; k <= gridSizeX; k += largeStep)
{
GL.Vertex3( startX + k, startY + offsetY, startZ + i);
GL.Vertex3( startX + k, gridSizeY + offsetY, startZ + i);
}
}
}
GL.End();
}
}
Thanks Em3rgency,, That is exactly what I was looking for!!!! Brilliant.. I could not up vote your answer cause I am new to the community..
Ahh yes, got something to add: You might want to change the drawing endpoints of the lines, or the grid won't work for origins different than 0.
Take X axis lines, for instance. Change the second vertex from
GL.Vertex3( gridSizeX, j + offsetY, startZ + i);
to
GL.Vertex3( startX + gridSizeX, j + offsetY, startZ + i);
How do you use the script? tried to attach it to a camera as a .cs but when is tarted the preview, unity froze.
Is it me or is this not working? Also is this memory efficient?
It is working. No idea about the memory efficiency, but I never encountered any hiccups.
That's not an answer. Don't use an answer for a question, ins$$anonymous$$d add a comment on the post your question is from.
Very nice script. You could improve readability by changing
plane.transform.position = new Vector3(plane.transform.position.x, plane.transform.position.y + smallStep, plane.transform.position.z);
to
plane.transform.position += smallStep * Vector3.up;
Answer by Ellandar · Mar 21, 2016 at 10:35 AM
As I can't edit posts yet, I figured I'd post an update to @Em3rgency's answer, I'm not entirely sure what correct forum decorum here is, so if this should be a comment to @Em3rgency's answer, then let me know and I'll do that.
This code works in Unity5 by incorporating @dpolyakov's answer and additionally fixes a bug that draw's the mesh incorrectly when setting StartX/Y/Z. I've also removed the grid moving functionality, as I couldn't see many use cases for that.
Same as before, put this in a C# script of it's own, and then ensure it gets attached to a Camera object.
using UnityEngine;
using System.Collections;
public class GridOverlay : MonoBehaviour
{
//public GameObject plane;
public bool showMain = true;
public bool showSub = false;
public int gridSizeX;
public int gridSizeY;
public int gridSizeZ;
public float smallStep;
public float largeStep;
public float startX;
public float startY;
public float startZ;
private Material lineMaterial;
public Color mainColor = new Color(0f, 1f, 0f, 1f);
public Color subColor = new Color(0f, 0.5f, 0f, 1f);
void CreateLineMaterial()
{
if (!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing
// simple colored things.
var shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
void OnPostRender()
{
CreateLineMaterial();
// set the current material
lineMaterial.SetPass(0);
GL.Begin(GL.LINES);
if (showSub)
{
GL.Color(subColor);
//Layers
for (float j = 0; j <= gridSizeY; j += smallStep)
{
//X axis lines
for (float i = 0; i <= gridSizeZ; i += smallStep)
{
GL.Vertex3(startX, startY + j , startZ + i);
GL.Vertex3(startX + gridSizeX, startY + j , startZ + i);
}
//Z axis lines
for (float i = 0; i <= gridSizeX; i += smallStep)
{
GL.Vertex3(startX + i, startY + j , startZ);
GL.Vertex3(startX + i, startY + j , startZ + gridSizeZ);
}
}
//Y axis lines
for (float i = 0; i <= gridSizeZ; i += smallStep)
{
for (float k = 0; k <= gridSizeX; k += smallStep)
{
GL.Vertex3(startX + k, startY , startZ + i);
GL.Vertex3(startX + k, startY + gridSizeY , startZ + i);
}
}
}
if (showMain)
{
GL.Color(mainColor);
//Layers
for (float j = 0; j <= gridSizeY; j += largeStep)
{
//X axis lines
for (float i = 0; i <= gridSizeZ; i += largeStep)
{
GL.Vertex3(startX, startY + j, startZ + i);
GL.Vertex3(startX + gridSizeX, startY + j , startZ + i);
}
//Z axis lines
for (float i = 0; i <= gridSizeX; i += largeStep)
{
GL.Vertex3(startX + i, startY + j , startZ);
GL.Vertex3(startX + i, startY + j , startZ + gridSizeZ);
}
}
//Y axis lines
for (float i = 0; i <= gridSizeZ; i += largeStep)
{
for (float k = 0; k <= gridSizeX; k += largeStep)
{
GL.Vertex3(startX + k, startY , startZ + i);
GL.Vertex3(startX + k, startY + gridSizeY , startZ + i);
}
}
}
GL.End();
}
}
Actually, even though the code works as advertised, here is one thing can be definitely improved: if gridSizeY parameter is 0 then a loop with comment "//Y axis lines" is not needed. This loop draws vertical lines to connect XZ-plane grids.
I agree it probably should bomb out when any of the gridSize values are 0. I don't think there's much of a performance overhead of triggering an empty for loop though. If that's the tallest poppy when optimising a game then I'm very impressed at the person's leet optimising skills, and I'd love lessons on optimisation from them!
Ell
You can optimize more, but it will not give you much performance boost: code like "startX + gridSizeX" in a loop can be precalculated.
What will give you a real boost if you are displaying a large grid - reduce amount of cells to draw. Like if your camera if high, why do you need to draw a small grid? It will look a way too small, almost solid grid, and it will kill your performance. You can display only the main grid in this case.
In my tests I did a very large grid (10,000x10,000). I cannot display it on my hardware - it takes almost a $$anonymous$$ute just to render it! So, to solve the problem, I "invented" a view port. Depending on my camera position, I calculate approximately how big my view port should be and I calculate what part of a grid to display. Like that I display only few cells that actually I can see. Also, I manipulate with large grid step: if a camera is too far, I scale big step proportionally. Basically, if my camera is too far: I see a big picture, if too close, I see details, like small steps.
Hey, every time i run this script my computer freezes, is there something i'm doing wrong or its simply because my computer cant handle the rendering?
also, when i implement the script, what exactly are the steps i have to make? like: 1.Add the script to the main camera 2.... .... .... Sorry, im just learning unity and the program$$anonymous$$g code too. THanks
the easiest way to figure it out: comment out everything and start uncommenting piece by piece and see where it freezes.
ok, i will try that. Do i need to make a game object, in this case a plane for it to work? and also should i be able to see the script working on the scene view or after i hit play ?
It froze up on $$anonymous$$e as well.... literally killed Unity. I'm not going to bother commenting out code to see where it freezes.
I just wanted to warn people who use the above script that they need to save their project first!!!! before even trying to implement this script... or else you'll lose an hours work like I did.
What did you set the variables to frankmat, and what version of Unity are you running? I expect large grids would take a long time to render, basically squeezing out everything else and locking unity. Probably other edge cases there too.
I tried this in a few projects and it's been ok, using 5.01. It's a little late now, but please do keep in $$anonymous$$d that you should always use code from any forum in a new empty project first (just as you should mods/add-ons you are updating or using for the first time). There are so many combinations of hardware/software versions/drivers etc. out there that there is never any guarantee any code will work cleanly on your pc.
Ell
Thanks for updating and cleaning up my old answer ;)
I remember I was quite drunk when I wrote it, working on my "super awesome next gen $$anonymous$$ecraft in space"... aaand space engineers came out. Good times lmao.
This grid boosted me up to mod status pretty much single handed. I'm happy to see people are still using it ^.^
I cleaned up Ellandars code a bit, removing the subGrid, adding a check for a 0 step value and renamed some variables to make more sense. Remember to set the step value to greater than 0.
GIST: https://gist.github.com/Andrioden/1e41e3fefc20270d413cec2818c02c11
Just to resurrect this code a little because it recently helped me with a game I'm making, I made one change to the code which i feel others may find useful.
The change i made allows for the small grid to follow the camera while staying snapped to the grid.
the only part i changed was having a reference to the camera and the if (showSub) section so here it is...
if (showSub)
{
GL.Color(subColor);
Vector3 center = new Vector3($$anonymous$$athf.Floor(camera.transform.position.x - (gridSizeX / 2)), startY, $$anonymous$$athf.Floor(camera.transform.position.z));
//Layers
for (float j = 0; j <= gridSizeY; j += smallStep)
{
//X axis lines
for (float i = 0; i <= gridSizeZ; i += smallStep)
{
GL.Vertex3(center.x, startY + j, center.z + i);
GL.Vertex3(center.x + gridSizeX, startY + j, center.z + i);
}
//Z axis lines
for (float i = 0; i <= gridSizeX; i += smallStep)
{
GL.Vertex3(center.x + i, startY + j, center.z);
GL.Vertex3(center.x + i, startY + j, center.z + gridSizeZ);
}
}
//Y axis lines
for (float i = 0; i <= gridSizeZ; i += smallStep)
{
for (float k = 0; k <= gridSizeX; k += smallStep)
{
GL.Vertex3(center.x + k, startY, center.z + i);
GL.Vertex3(center.x + k, startY + gridSizeY, center.z + i);
}
}
}
Answer by jrat · Aug 14, 2015 at 03:21 PM
An easier way to do it is to use a tiled material:
1) Create and import an square image with a transparent background and a solid square frame around the edge.
2) Create a material, set it's shader to "Transparent/Diffuse", and drag your image onto it.
3) Set the "Tiling" fields of the material to your grid dimensions.
4) Create a Quad GameObject, scale it to whatever size you want the grid to be, and attach the material to it.
Often times this solution messes up gameobjects filtering, raycasts, triggers etc However, for simples scenes in non-mobile, simplicity like this rocks
Great solution, the only problem is inner lines are wider than outer lines. $$anonymous$$ight be a problem or not, depending on your situation.
Answer by row1 · Dec 29, 2013 at 09:17 AM
I don't have enough rep to edit Em3rgency's post, but his solution requires a modification to render the colours correctly on Android--they will currently render as black.
I have changed CreateLineMaterial
to GetLineMaterial
and commented out the calls to GL.Color
.
private IDictionary<Color, Material> materialsByColor = new Dictionary<Color, Material>();
private Material GetLineMaterial(Color color)
{
Material lineMaterial;
if( !materialsByColor.TryGetValue(color, out lineMaterial) )
{
lineMaterial = new Material( "Shader \"Lines/Colored Blended\" {" +
" Properties { _Color (\"Main Color\", Color) = ("+color.r+","+color.g+","+color.b+","+color.a+") } " +
" SubShader { Pass { " +
" Blend SrcAlpha OneMinusSrcAlpha " +
" ZWrite Off Cull Off Fog { Mode Off } " +
" Color[_Color] " +
" BindChannels {" +
" Bind \"vertex\", vertex Bind \"color\", color }" +
"} } }" );
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
materialsByColor.Add(color, lineMaterial);
}
return lineMaterial;
}
I then call it like so:
GL.Begin( GL.LINES );
if(showSub)
{
//GL.Color(subColor);
var lineMaterial = GetLineMaterial(subColor);
lineMaterial.SetPass( 0 );
Answer by dpolyakov · Mar 06, 2016 at 02:55 PM
to make colors to display properly in Unity5 you need to modify CreateLineMaterial():
void CreateLineMaterial()
{
if(!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing
// simple colored things.
var shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
Thanks. I noticed that the color was pink in the new Unity versions.
Your answer

Follow this Question
Related Questions
I need a grid to help me model and design things. 4 Answers
Why can't I view my grid? 1 Answer
Cloud recognition in Vuforia 0 Answers
How to create a 14 by 12 grid, depending on screen size? 1 Answer
Shotgun Spread Issue 1 Answer