How to make Minesweeper game in Unity?

Hi, I created Minesweeper game in WPF (Windows Presentation Foundation) using .NET and C#. Now, I’m trying to do the same but in Unity. Problem is: How to draw a Grid? How to insert text in cells? How to change color of cell when Mouse enters the cell (do I need two prefabs for that or only one)? Any help is welcome. Thanks.

Hi Borko, here’s how I would do it:
Please note this is just one way to do it. There are plenty of other ways.

Use the “Grid Layout Group” component on a Canvas to force its children into a grid.
Make a prefab (I will call it “Cell”) consisting of 2 game objects:

  • The parent object will have a RawImage component attached. Use the “Color” property to change the cell color.
  • The child object will have a Text component attached, center-aligned both vertically and horizontally.

It’s better practice to just have 1 prefab and a script that can change the color.

Create a script component (I will call it “CellHandler”) that will be attached to each Cell.
Something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CellHandler : MonoBehaviour
{

    void Start()
    {
       
    }

    public void ChangeSelected(bool selected)
    {
        var image = GetComponentInChildren<UnityEngine.UI.RawImage>();
        Debug.Assert(image != null, "Image component not found.");

        if (selected)
            image.color = Color.blue;
        else
            image.color = Color.gray;

    }

}

Attach an “Event Trigger” component to the Cell, and add the “PointerEnter” and “PointerExit” event types.
Direct these events to trigger the “ChangeSelected” function on your cell, like so:

All together:

1 Like

You could also (maybe) use a tilemap system, it’s a bit harder, but that could let you do way more stuff than the UI system, you could add a lot of fancy graphics to your Minesweeper.
That would also do a great intermediate learning session to Unity tilemap system.

1 Like