Categories
Code Development Uncategorized

Overbuilding a Grid in Unity

I can say pretty confidently that over the last 5 years I have made and re-made some sort of grid system in Unity close to a half dozen times. Its not particularly complicated but it is another example of time I’ve wasted. Much like the debugger, I saw another opportunity to add a tool to my library.

At its core, what I needed was something that would generate a collection of points given certain parameters. Additionally I wanted to cram a bunch of helper methods/properties that would make using the grid and reading the implementation intuitive. All we are really doing is adding some additional functionality around a collection of grid points so I saw this as a perfect opportunity for a custom collection class.

    
    public class Grid2D : IEnumerable<Vector2>
    {
        private List<Vector2> gridPoints = new List<Vector2>();

        public IEnumerator<Vector2> GetEnumerator() => gridPoints.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)gridPoints).GetEnumerator();
    }

At this point the Grid2D class is just a fancy name for an IEnumerable<Vector2>—list of x, y coordinates—and we could use it as such. What makes is shine is when we add some utility methods and properties that make common operations more accessible. For example, lets say I wanted to get the corner points:

    
    public Vector2 TopLeftCorner => new Vector2(
        XMin - (CellWidth / 2),
        YMax + (CellHeight / 2));

    public Vector2 TopRightCorner => new Vector2(
        XMax + (CellWidth / 2),
        YMax + (CellHeight / 2));

    public Vector2 BottomRightCorner => new Vector2(
        XMax + (CellWidth / 2),
        YMin - (CellHeight / 2));

    public Vector2 BottomLeftCorner => new Vector2(
        XMin - (CellWidth / 2),
        YMin - (CellHeight / 2));

Or maybe I wanted just the top row:

    // Rows
    public IEnumerable<Vector2> RowTop => gridPoints
        .Where(p => p.y == YMax);

    // Y
    public float YMax => gridPoints
        .Select(p => p.y).Max();    

I probably added more than what I needed but all in service to readability and ease of use.

Properties that make common operations easier and read well

I’ve added quite a bit more to this class and it will probably be changing a bit further once I actually start using it. Feel free to check out the full code on my GitHub page linked here or in the footer.