Search Unity

drawing a grid crahes editor and game.

Discussion in 'General Graphics' started by Skreamz, May 31, 2016.

  1. Skreamz

    Skreamz

    Joined:
    Jan 8, 2015
    Posts:
    13
    hi all. i've got code to draw a grid. which crashes may game. plus causes the editor to do the same when loading up as default scene.

    if anyone can see whats wrong, please let me know.


    using UnityEngine;
    using System.Collections;

    [ExecuteInEditMode]
    public class DrawGrid : MonoBehaviour
    {
    // When added to an object, draws colored rays from the
    // transform position.
    public float positiontop;
    public float positionbottom;
    public float positionfromleft;
    public float positionfromright;
    public int rows;
    public int collumns;

    float positionleft;
    float positionright;

    static Material lineMaterial;

    static 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);
    }
    }

    public void Update()
    {
    float vert = Camera.main.GetComponent<Camera>().orthographicSize;

    positionleft = -(vert * Screen.width / Screen.height);
    positionright = -positionleft;

    positionleft += positionfromleft;
    positionright -= positionfromright;
    }

    // Will be called after all regular rendering is done
    public void OnRenderObject ()
    {
    CreateLineMaterial ();
    // Apply the line material
    lineMaterial.SetPass (0);

    GL.PushMatrix ();
    // Set transformation matrix for drawing to
    // match our transform
    //GL.MultMatrix (transform.localToWorldMatrix);

    // Draw lines
    GL.Begin (GL.LINES);

    GL.Color (new Color (1, 1, 1, 1));

    float width = positionright - positionleft;
    float heigt = positiontop - positionbottom;
    float boxwidth = width / collumns;
    float boxheight = heigt / rows;

    //draw grid vertical
    for(float x = positionleft; x <= positionright; x += boxwidth)
    {
    GL.Vertex3 (x, positiontop, 0);
    GL.Vertex3 (x, positionbottom, 0);
    }

    //draw grid horizontal
    for(float y = positionbottom; y <= positiontop; y += boxheight)
    {
    GL.Vertex3 (positionleft, y, 0);
    GL.Vertex3 (positionright, y, 0);
    }

    GL.End ();
    GL.PopMatrix ();
    }
    }