Drawing a 2D grid on a 3D plane... UnityEngine.UI?

I am attempting to draw a 2D grid on a plane (which is my “floor”) as a sort of game board. I have made a script to generate a texture to render:

void GenerateGrid()
    {
        Color gridColor = Color.cyan;
        Color borderColor = Color.black;
        Collider floorCollider = floor.GetComponent<Collider>();
        Vector3 foorSize = new Vector3(floorCollider.bounds.size.x, floorCollider.bounds.size.z);
        for (int x = 0; x < gridImage.width; x++)
        {
            for (int y = 0; y < gridImage.height; y++)
            {
                if (x < borderSize || x > gridImage.width - borderSize || y < borderSize || y > gridImage.height - borderSize)
                {
                    gridImage.SetPixel(x, y, new Color(borderColor.r, borderColor.g, borderColor.b, 50));
                }
                else gridImage.SetPixel(x, y, new Color(gridColor.r, gridColor.g, gridColor.b, 50));
            }
            gridImage.Apply();
        }

    }

However, I cannot for the life of me think of any way to draw this texture multiple times in a grid format onto the plane in question. I have checked the documentation and was trying to see if I could use Graphics.DrawTexture() or anything of the like that would help me. Maybe I was using it wrong. I really don’t want to instanciate hundreds of gameobjects in the shape of a grid though… any advice?

Welp, answered my own question. For anybody else’s reference i just did this:

gridImage.wrapMode = TextureWrapMode.Repeat;
        floor.GetComponent<MeshRenderer>().material.SetTexture(1, gridImage);
        floor.GetComponent<MeshRenderer>().material.SetTextureScale(1, new Vector2(floorCollider.bounds.size.x, floorCollider.bounds.size.z));
1 Like

Just kidding. I’m getting a weird issue here: grid shows beautifully in the editor while running. However: it doesn’t show in my build version

editor:
:

build:

Welp, I figured that but out as well. Code update is:

MeshRenderer floorRenderer = floor.GetComponent<MeshRenderer>();
        floorRenderer.material.mainTexture = gridImage;
        floorRenderer.material.mainTextureScale = new Vector2(floorCollider.bounds.size.x, floorCollider.bounds.size.z);
        floorRenderer.material.mainTextureOffset = new Vector2(.5f, .5f);

I suppose I should spend more time debugging than browsing the forums ;). At least this will help out others who want to do the same!

EDIT: the problem was that i was adding a new texture to the material instead of setting the MainTexture. Code works perfectly now :slight_smile:

@ Hey man, I am trying to achieve the same thing you did but when i copy your code and add my own texture and floor game object; Unity just crashes on play. Any ideas how can i fix this? Or can you share the latest working code so i can learn?

2 Likes