Making your own cells

Grids come with a few minimal cells, but for your own game you will probably use cells that are better suited for the game you are making.

Here are a few examples of typical cases where you want to make your own cells:

  • To support switching to a different sprite or changes color when clicked.
  • To support a cell that displayes text.
  • To support a cell that knows whether it is accessible for using your grid with AStar.
  • To support a cell that display different sprites depending on its “type” (for example, you may have different terrain types).
  • To support cells that can be “empty”.

To make your own cell is easy. In general, cells can be of any type. However, you may want to choose a specific base type as explained here:

  • If you want your cells to display in the scene as game objects, you need to make your own cell extend from at least MonoBehaviour.
  • If you want to use your cells with Grid Builders (so that you can build your grid in the editor, and not just in code), your class needs to extend from TileCell.
  • Check whether one of the built-in cells is a good starting point.
    • For 2D games that use sprites, SpriteCell is a good base class.
    • For games that use models for tiles (such as cubes or something more complicated), Block is a good base class.
    • For games that have custom meshes (such as polar grids), MeshTileCell is a good base class.

Here are a few guidelines when implementing cells:

  • Avoid making cells know their grid positions. This is often difficult to maintain (especially if you swap cells or move them), and can lead to more intricate main logic.
  • Avoid making cells know their neighbors. As above, this can lead to more intricate main logic.
  • Keep cells as dumb as possible. Cells can keep state, but should not (usually) calculate their own state. Their state should be calculated by the main logic, and then set from there.
  • Use the following idiom to update presentation based on state:
    public class MyCell: MonoBehaviour
       //Keep states private
       private State1 state1;
       private State2 state2;
       //Provide public properties to change the state
       public State1 State1
          get { return state1; }
             state1 = value;
             UpdatePresentation(); //Update presentation to display new state.
       public State2 State2
          get { return state2; }
             state2 = value;
       private void UpdatePresentation()
          //logic to change cells appearance based on two states
  • It is useful to use a ScriptableObject to manage tile sets. See Making custom cells and using scriptable objects to manage tile sets.

1 thought on “Making your own cells”

  1. Pingback: Game Development with Unity 2D – part 5: A grid of Roman centuriae - Design a Game

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top