skip to Main Content

Scripting Support (C#)

Snippets

Note for new developers!

If you’re new to programming, you may find overwhelmed by the large list of C# functions and properties. We have created a few useful scripts for new developers called “Snippets”. They’re scripts you can add to gameobjects to perform simple tasks, like “move this object to target cell” without coding.

These snippets are just fancy wrappers for the API provided by Terrain Grid System so you can take a look into them and learn how do they use the API.

The available snippets can be found in the Component menu:

For example, let’s say you have a gameobject you want to move on the grid. You can add the script “TGS Move To Cell” to your gameobject and enter the row and column in the inspector:

The available snippets are:

  • TGS Clear Cells
  • TGS Color Neighbours
  • TGS Detect Movement
  • TGS Move To Cell
  • TGS Move To Cell With PathFind

If you would like more snippets or have any question please send us an email or use our support forum. We’ll gladly add more snippets for you 

Check the demo scene Demo19_SnippetsExample.

Important! These snippets just provide like the 1% of functionality provided by the API and are meant to introduce you into some common features. If you already know how to program in C# then you can go directly to the next section and learn the API (it’s not that complex after all!).

 

Use Terrain Grid System from scripting

You can instantiate the prefab “TerrainGridSystem“ or add it to the scene from the Editor as explained in the “How to use this asset in your project” section. Once the prefab is in the scene, you can access the functionality from code through the static instance property:

using TGS;

TerrainGridSystem tgs;

void Start () {
tgs = TerrainGridSystem.instance;
...
}

To get the cell beneath a gameobject in your scene use CellGetAtPosition and pass the world space coordinate:

Cell cell = tgs.CellGetAtPosition(Vector3 position, Vector3 wordSpace);

To fade surrounding cells:

List<Cell>neighbours = tgs.CellGetNeighbours(sphereCell);

foreach(Cell cell in neighbours){
tgs.CellFadeOut(cell, Color.red, 2.0f)
}

To fade cells by row and column:

const int size = 3; for (int j=sphereCell.row - size; j<=sphereCell.row + size;j++) {
for (int k=sphereCell.column - size; k<=sphereCell.column + size; k++) {
            int cellIndex = tgs.CellGetIndex(j,k, true);
            tgs.CellFadeOut(cellIndex, Color.blue, 1.0f);
       }
}

Another example, If you want to create a new Territory and add a cell to it, you can do this:

Territory territory = new Territory("new territory"); 
tgs.territories.Add(territory); 
int newTerritoryIndex = tgs.territories.Add(territory); 
tgs.CellSetTerritory(cellIndex, newTerritoryIndex);

Take a look at the demo scenes included in the asset for more sample code!

Public API Structure

All TerrainGridSystem API is exposed through TerrainGridSystem class. This is a single component that has been split for convenience in several files located in TerrainGridSystem/Scripts folder:

  • TerrainGridSystem: contains generic functions and properties.

  • TGSCells: all cell-related.

  • TGSTerritories: all territory-related.

  • TGSPathfinding: pathfinding stuff.

  • TGSConfig: this is the component that stores the cell configuration when you use and export the cell setup using the Grid Editor.

Note that the above are just filenames, but the class is the same “TerrainGridSystem”. This approach follows the partial class standard in C# to make easy the reorganization of “God” (or big) utility classes. This means that you will be just using the traditional gameObject.GetComponent<TerrainGridSystem>() or just TerrainGridSystem.instance to get a reference to the API, irrespective of the number of classes files.

Thanks to this file organization you can easily check the different public properties and functions of the API by category (cell-related, territory-related, …)

Complete list of public properties, methods and events

Basic grid functions

tgs.SetTerrain(gameObject): specifies the terrain gameobject linked to the grid. Usually this is set in Editor time but you can also call thi method if you instantiate the prefab at runtime. Instead of instantiating the prefab you can just call AddTerrainGridSystem() directly on any gameobject including your terrain gameobject (AddTerrainGridSystem is an extension method for GameObject class).

tgs.numCells: desired number of cells for irregular topology. The actual generated cells will vary depending on the topology.

tgs.ColumnCount: number of columns for boxed and hexagonal types.

tgs.RowCount: number of rows for boxed and hexagonal types.

tgs.SetDimensions(int rows, int columns, bool keepCellSize): sets the number of rows and columns in one step (only hexagonal or box grid topology). This is faster than settings rowCount and columnCount separately. The parameter keepCellSize determines if the individual cell size is preserved (only valid for hexagonal and box topologies).

tgs.seed: seed constant for the random generator.

tgs.gridCenter: the center of the grid with respect to its parent (0,0 = center).

tgs.gridCenterWorldPosition: sets or retrieves the center of the grid in world space coordinates. You can also call tgs.SetGridCenterWorldPosition method instead.

tgs.gridScale: the scale of the grid with respect to its parent (1,1 = full terrain/grid size)

tgs.cellSize: directly sets the individual cell size (Vector2). Setting this property will recalculate the grid scale accordingly.

tgs.gridMask: optional texture used to defined cells visibility. The texture is matched against the whole grid parent surface. An alpha value of 0 means cell will be invisible.

tgs.gridTopology: type of cells (Irregular, Box, Hexagonal, …)

tgs.gridRelaxation: relaxation factor for the irregular topology (defaults 1). It creates more homogeneous irregular grids but has a performance hit during the creation of the grid (not afterwards).

tgs.gridCurvature: will bend cell edges for all topologies. It will add more vertex count to the mesh so it’s only available on grids with less than 100 cells.

tgs.terrainCenter: returns the world space position of the center of the terrain.

tgs.bounds: the bounds of the grid in world space. This property does not account for height.

tgs.gridElevation: vertical offset of the grid with respect to the terrain for fine-tuning z-fighting issues.

tgs.gridElevationBase: vertical position for the grid, used to elevate grid over terrain. Both gridElevation and gridElevationBase are added when computing the position of the grid. Use gridElevationBase if you want the grid to float above the terrain and gridElevation for small height adjustments.

tgs.gridCameraOffset: dynamic camera-oriented displacement. This will move the mesh towards the camera.

tgs.gridNormalOffset: general offset of the mesh from the terrain. This will make the grid “grow” in all directions. This will impact performance during the mesh creation.

tgs.gridDepthOffset: Z-Buffer offset for the grid system shaders. Very cheap method to prevent z-fighting which can be combined with above methods. You should use this property first to adjust your grid.

tgs.gridRoughness: gripping factor for the mesh. The lower the value the better fit of the mesh to the terrain.

tgs.nearClipFade: distance from the camera for the fade in effect of the grid. Useful in first-person-view games.

tgs.nearClipFadeFallOff: falloff or gradient amount for the fade in effect.

tgs.voronoiSites: optionally set a list of starting Voronoi site positions. The list will be completed up to numCells if voronoiSites list provided has less items.

Cells related

PROPERTIES

tgs.cells: return a List<Cell> of all cells/states records.

tgs.showCells: whether to show or not the cells borders.

tgs.cellHighlighted: returns the cell/state object in the cells list under the mouse cursor (or null if none).

tgs.cellHighlightedIndex: returns the cell/state index in the cells list under the mouse cursor (or -1 if none).

tgs.cellHighlightNonVisible: sets if invisible cells should be highlighted when pointer is over them (default is true).

tgs.cellLastClickedIndex: returns the index of last cell clicked.

tgs.cellHighlightColor: color for the highlight of cells.

tgs.cellHighlightNonVisible: set to true if you want to be able to highlight invisible cells.

tgs.cellBorderColor color for all cells borders.

tgs.cellBorderAlpha: helper method to change only the alpha of cell borders.

METHODS

tgs.CellSetTag(int cellIndex, int tag): assigns a cell a user-defined integer tag. Cell can be later retrieved very quickly with CellGetWithTag.

tgs.CellGetWithTag(int tag): retrieves a cell previously tagged with an integer using the method CellSetTag.

tgs.CellGetIndex(Cell cell): returns the index of the provided cell object in the Cells collection.

tgs.CellGetIndex(row, column, clampToBorders): returns the index of the provided Cell by row and column. Use clampToBorders = true to limit row/column to edges of the grid or to allow wrap around edges otherwise.

tgs.CellGetPosition(int cellIndex): returns the geometric center of the enclosing rectangle of the cell in the world space.

tgs.CellGetCentroid(int cellIndex): returns the centroid of the cell in world space (the centroid always lays inside the polygon). There is a demo featuring this in scene 13.

tgs.CellGetRect(int cellIndex): returns the 2D rectangle enclosing the cell in local space (-0.5..0.5 range).

tgs.CellGetRectWorldSpace(int cellIndex): returns the 3D bounds of the cell in world space.

tgs.CellGetVertexCount(int cellIndex): returns the number of vértices of any cell.

tgs.CellGetVertexPosition(int cellIndex, int vertexIndex): returns the world space position of any vertex of a cell.

tgs.CellGetAtPosition(Vector3 position, Vector3 wordSpace): returns the cell that contains position (in local space coordinates which ranges from -0.5 to 0.5 or from a point in world space).

tgs.CellGetAtPosition(int column, int row): returns the cell located at given row and col (only boxed and hexagonal topologies).

tgs.CellGetInArea(Bounds bounds, List<int>indices, float padding = 0, bool checkAllVertices = false)

Returns a list of cell indices contained in the bounds or under those bounds (eg. under a gameobject’s collider bounds). Padding is an optional margin that adds or substract to the boundary. When checkAllVertices is true, not only the center but all cell vertices are checked.

tgs.CellGetInArea(Collider collider, List<int>indices, int resolution, float padding = 0, float offset = 0)

Returns a list of cell indices contained under a collider. Resolution and padding are used to defined the granularity of the algorithm which tests cells inside the projected collider bounds. Offset can be used to modify the projection axis. This method can now use a new overload: GameObject gameobject. 

tgs.CellGetWithinCone(int cellIndex, Vector2 direction, float maxDistance, float angle, List<int> cellIndices)

Returns a list of cells contained in a cone defined by a starting cell, a direction, max distance and angle in degrees (max distance is defined in local space coordinates of grid being the borders at -0.5 and 0.5)

tgs.GetCellsWithinCone(int cellIndex, int targetCellIndex, float angle, List<int> cellIndices)

Returns a list of cells contained in a cone defined by a starting cell, target cell and angle in degrees.

tgs.CellGetNeighbour(int cellIndex, int side): returns the index of the adjacent cell by its side name (top, right, bottom left, …).

tgs.CellGetNeighbours(int cellIndex, …): returns a list of neighbour cells to a specific cell optionally specifying the maximum number of steps, maximum total cross cost, cell group mask and other options.

tgs.CellGetNeighboursWithinRange(int cellIndex, …): similar to CellGetNighbours method but accepts min and max distance.

tgs.CellExpandSelection(List<int> cellIndices): adds surrounding cells to the given list of cells.

tgs.CellGetHexagonDistance(index1, index2): returns the number of steps to reach cell2 from cell1 in an hexagonal grid. This method does not take into account cell groups nor blocking cells.

tgs.CellMerge(Cell 1, Cell 2): merges two cells into the first one.

tgs.CellSetTerritory(int cellIndex, int territoryIndex): changes the territory of a cell and updates boundaries. Call Redraw() to update the grid afterwards.

tgs.CellToggleRegionSurface(cellIndex, visible, color, refreshGeometry): colorize one cell’s surface with specified color. Use refreshGeometry to ignore cached surfaces (usually you won’t do this).

tgs.CellToggleRegionSurface(cellIndex, visible, color, refreshGeometry, texture): color and texture one cell’s surface with specified color. Use refreshGeometry to ignore cached surfaces (usually you won’t do this). Texture can be scaled, panned and/or rotated adding optional parameters to this function call.

tgs.CellToggleRegionSurface(int cellIndex, bool visible, Color color, bool refreshGeometry, Texture2D texture, Vector2 textureScale, float textureRotation, bool overlay): same but allows to specify a texture scale and rotation and optionally if the colored surface will be shown on top of objects.

tgs.CellHideRegionSurface(int cellIndex): uncolorize/clears one cell’s surface.

tgs.CellHideRegionSurfaces(): uncolorize/clears all cells.

tgs.CellFadeOut(int cellIndex, color, duration, repetitions): colorizes a cell and fades it out for duration in seconds.

tgs.CellFlash(int cellIndex, color, duration, repetitions): flashes a cell from given color to default cell color for duration in seconds.

tgs.CellBlink(int cellIndex, color, duration, repetitions): blinks a cell from current color to a given color and back to original cell color for duration in seconds.

tgs.CellColorTemp(int cellIndex, color, duration): temporarily colors a cell or group of cells.

tgs.CellCancelAnimations(cellIndex): removes any effect on a cell or group of cells.

tgs.CellGetColor(cellIndex): returns current cell’s fill color.

tgs.CellGetTexture(cellIndex): returns current cell’s fill texture.

tgs.CellSetTexture(cellIndex, texture): sets the texture for a cell. Similar to CellToggleRegionSurface.

tgs.CellSetTexture(cellIndex, texture, tintColor): sets the texture for a cell and applies a tint color. Similar to CellToggleRegionSurface.

tgs.CellSetColor(cellIndex, color): sets the color for a cell. Similar to CellToggleRegionSurface.

tgs.CellSetMaterial(cellIndex, material): assigns user defined material to a cell.

tgs.CellGetNormal(cellIndex): returns the terrain normal at the center of the cell.

tgs.CellIsBorder: returns true if the cell sits at the edges of the grid.

tgs.CellIsVisible: returns true if the cell is visible.

tgs.CellSetVisible: makes a cell or group of cells visible or invisible.

tgs.CellSetBorderVisible: makes a cell’s border visible or invisible.

tgs.CellGetGameObject: returns the cell surface gameobject.

tgs.CellGetExtrudedGameObject: returns an extruded version of a cell surface.

tgs.CellScaleSurface: applies a scale to a colored/textured cell surface.

tgs.CellRemove: completely removes a cell from the grid. Call Redraw() to update the grid afterwards.

tgs.CellSetCanCross(int cellIndex, bool canCross, List<int>cellIndices): specifies if a cell can be part of a route returned by Pathfinding methods. This method is used to specify blocking cells.

tgs.CellSetGroup: assigns a cell to a group. Groups can be used to use certain cells or not when calling FindPath, CellGetNeigbhours or CellGetLineOfSight. Using groups you can create different kind of blocking cells. See demo scene 12 for an example.

tgs.CellGetGroup: gets the group of a cell.

tgs.CellGetFromGroup: gets all cell indices from a group.

tgs.CellSetSideCrossCost/CellGetSideCrossCost: sets or obtain the crossing cost for a cell and a specific edge with option to apply that cost to any direction (ie. existing or entering the cell through that edge).

tgs.CellSetAllSidesCrossCost: convenient method to quickly assign a crossing cost to a cell regardless of the edge used to travel.

tgs.CellGetConfigurationData: retrieves a string-packed description of the cells properties. Use CellSetConfigurationData to load the configuration.

tgs.CellSetConfigurationData: loads a configuration of cells from a string.

tgs.CellGetSettings: similar to CellGetConfigurationData but returns an array of TGSConfigEntry values (one per cell). A TGSConfigEntry is a struct that contains important attributes about each cell.

tgs.CellSetSettings: similar to CellSetConfigurationData but accepts an array of TGSConfigEntry values.

tgs.CellAddSprite(int cellIndex, Sprite sprite, bool adjustScale): creates a gameobject with a given sprite and positions/scale it to match a given cell.

tgs.CellGetExtrudedGameObject(int cellIndex, float extrusionAmount): creates an extruded version of the given cell and returns it as a gameobject.

tgs.CellIsAdjacentToTerritory(int cellIndex, int territoryIndex): checks if the given cell is neighbour to the given territory. 

 tgs.CellIsAdjacentToCell(int cellIndex, int otherCellIndex): checks if a cell is neighbour to another.

tgs. CellDrawBorder(Cell cell, Color color = default, float thickness = 0): draws and returns a gameobject with the border of the given cell. 

tgs.CellDestroyBorder(int cellIndex): destroys a border previously drawn using the CellDrawBorder method.

tgs.CellSetOverlayMode(int cellIndex, bool overlayMode): sets if a cell color should be displayed on top.

tgs.CellGetOverlayMode(int cellIndex): returns true if the cell is in overlay mode (shows on top).

Cell class

Each entry in tgs.cells is a Cell object. For example, tgs.cells[0] is the first cell in the array.
You should always test that a cell entry is not null.

The cell class contains basic information about each cell:

cell.territoryIndex: the index of the territory to which the cell belongs.

cell.index: the index of the array in the tgs.cells array.

cell.row / cell.column: the row and column of the cell (in box/hexagonal topologies)

cell.tag: user defined custom value, useful to store some info.

cell.attrib: a jSON object to store custom properties in this cell.

Other properties should be managed only through the available Cell**** methods.

Territory related

PROPERTIES

tgs.numTerritoriess: desired number of territories (1-number of cells).

tgs.territories: return a List<Territory> of all territories.

tgs.showTerritories: whether to show or not the territories borders.

tgs.showTerritoriesOuterBorder: whether to show or not the territories perimeter around the grid.

tgs.territoryHighlighted: returns the Territory object for the territory under the mouse cursor (or null).

tgs.territoryHighlightedIndex: returns the index of territory under the mouse cursor (or -1 if none).

tgs.territoryLastClickedIndex: returns the index of last territory clicked.

tgs.territoryHighlightColor: color for the highlight of territories.

tgs.territoryFrontiersColor: color for all territory frontiers.

tgs.territoryDisputedFrontiersColor: color for shared frontiers between two territories.

tgs.territoryFrontiersAlpha: helper method to change only the alpha of territory frontiers.

tgs.colorizeTerritories: whether to fill or not the territories.

tgs.colorizedTerritoriesAlpha: transparency level for colorized territories.

tgs.territoryInteriorBorderPadding: measure of the distance between the cell polygon and the interior border itself. 

tgs. territoryInteriorBorderThickness: measure of the interior border’s thickness.

METHODS

tgs.TerritoryToggleRegionSurface(territoryIndex, visible, color, refreshGeometry): colorize one territory’s surface with specified color. Use refreshGeometry to ignore cached surfaces (usually you won’t do this).

tgs.TerritoryToggleRegionSurface(territoryIndex, visible, color, refreshGeometry, texture): color and texture one territory’s surface with specified color. Use refreshGeometry to ignore cached surfaces (usually you won’t do this). Texture can be scaled, panned and/or rotated adding optional parameters to this function call.

tgs.TerritoryToggleRegionSurface(cellIndex, visible, color, refreshGeometry, texture, textureScale, textureRotation, overlay): same but allows to specify a texture scale and rotation and optionally if the colored surface will be shown on top of objects.

tgs.TerritorySetMaterial(territoryIndex, material): assigns user defined material to a territory.

tgs.TerritoryHideRegionSurface(territoryIndex): uncolorize/clears one territory’s surface.

tgs.TerritoryGetNeighbours(territoryIndex): returns a list of neighbour territories to a specific territory.

tgs.TerritoryGetCells(territoryIndex, regionIndex): returns a list of cells belonging to a territory or any of its regions.

tgs.TerritoryGetAtPosition(position): returns the territory that contains position (in local space coordinates).

tgs.TerritoryGetPosition(territoryIndex): returns the geometric center of the enclosing rectangle of the territory in world space. Now enhanced to be more precise.

tgs.TerritoryGetCentroid(territoryIndex): returns the centroid of the territory in world space (the centroid always lays inside the polygon).

tgs.TerritoryGetRectWorldSpace(territoryIndex): returns the boundaries of the territory in world space coordinates.

tgs.TerritoryGetVertexCount(territoryIndex): returns the number of points of the territory polygon.

tgs.TerritoryGetVertexPosition(territoryIndex, vertexIndex): returns the position of the specified vertex in world space coordinates.

tgs.TerritoryFadeOut(territoryIndex, color, duration, repetitions): colorizes a territory and fades it out for duration in seconds.

tgs.TerritoryFlash(territoryIndex, color, duration, repetitions): flashes a territory from given color to default territory color for duration in seconds.

tgs.TerritoryBlink(territoryIndex, color, duration, repetitions): blinks a territory from current color to a given color and back to original territory color for duration in seconds.

tgs.TerritoryColorTemp(cellIndex, color, duration): temporarily colors a territory or group of territories.

tgs.TerritoryCancelAnimations(territoryIndex): removes any effect on a territory.

tgs.TerritoryIsVisible(territoryIndex): returns true if territory is visible.

tgs.TerritorySetVisible(territoryIndex): makes a territory visible or invisible.

tgs.TerritorySetBorderVisible: makes a territory’s border visible or invisible.

tgs.TerritorySetFrontierColor(territoryIndex, color): assigns a new color for the frontiers of a given territory.

tgs.CreateTerritories(texture, neutral): generate territories based on distinct colors contained in the provided texture ignoring neutral color.

tgs.TerritorySetNeutral(territoryIndex, neutral): specifies if a given territory should be considered as neutral. Neutral territories do not dispute frontiers.

tgs.TerritoryIsNeutral(territoryIndex): returns true if the given territory is neutral.

tgs.TerritoryGetFrontier(territoryIndex, regionIndex): returns a list of points (Vector2) that form a territory frontier. 

tgs.TerritoryGetFrontierCells(territoryIndex, …): returns a list of cells that are on a territory frontier. Optionally restrict to frontier with another territory index. Can now filter by region and it also includes cells at the edge of the grid.

tgs.TerritoryGetAdjacentCells(territoryIndex, …): returns a list of cells that are on a territory frontier and belongs to the adjacent territory. Optionally restrict to frontier with another territory index. Can now filter by region.

tgs.TerritoryGetGameObject: returns the territory’s surface gameobject.

tgs.TerritoryScaleSurface: applies a scale to a colored/textured territory surface.

tgs.TerritoryDrawFrontier(territoryIndex, adjacentTerritoryIndex, material, color): draws the frontier around the territory specified by territoryIndex. Optional parameters include: adjacentTerritoryIndex (only draw frontier shared by those two territories), a material or a color.

Note: this method returns the gameobject for the newly drawn frontier. You’re responsible of disposing this gameobject or redrawing it since TGS won’t refresh it nor destroy it when changing the grid.

tgs.TerritoryHideInteriorBorders: destroys interior borders of all territories drawn with TerritoryDrawInteriorBorder method.

tgs.TerritoryDrawInteriorBorder(territoryIndex, padding, thickness, color, secondColor, regionIndex, animationSpeed): draws an interior border for a specific territory. Padding determines the separation of the interior border to the polygon. Thickness is the width of the border. Color and secondColor specify the color gradient range for the line. RegionIndex is optional and can be specified if the territory has more than one region. AnimationSpeed determines the speed of the color gradient animation. Check demo scene 27 for an example.

tgs.DrawCustomBorder(cells, color, thickness): computes and draws a border around a list of cells. Cells must be all connected.

tgs.TerritorySetColor(Territory territory, Color color, [int regionIndex= 0]): sets the color of the territory. 

tgs.TerritorySetTexture(Territory territory, Texture2D texture, [int regionIndex = 0]): sets the texture of a territory. 

tgs.TerritoryCreate(…): creates a territory given either a single cell or a list of cells.

tgs.TerritoryDestroy(int territoryIndex): removes an existing territory given its territoryIndex. Cells belonging to the removed territory will be freed.

tgs.TerritoryDestroyAll(): destroys all territories.

User interaction / Highlighting

tgs.highlightMode: choose between None, Territories or Cells. Defaults to Cells.

tgs.highlightFadeAmount: alpha range for the fading effect of highlighted cells/territories (0-1).

tgs.highlightMinimumTerrainDistance: minimum distance to the terrain to allow highlighting of cells/territories.

tgs.HighlightTerritoryRegion(territoryIndex, refreshGeometry, regionIndex): manually highlights a territory region. RefreshGeometry can be used to force creation of the highlight mesh (usually not required). RegionIndex can be used to highlight a specific region of a territory if it’s split in several zones (usually not required).

tgs.HideTerritoryRegionHighlight(territoryIndex): hides the highlight of the territory.

tgs.HighlightCellRegion(cellIndex, refreshGeometry): manually highlights a cell region.

tgs.HideCellRegionHiglight(cellIndex): hides the highlight of the cell.

tgs.overlayMode: decide whether the highlight is shown always on top or takes into account z-buffer which will make it more fancy and part of the scene.

tgs.localCursorPosition: the current cursor position on the grid (mouse over the grid) in local grid coordinates. Use tgs.transform.TransformPoint(x) method to convert to world space coordinates.

tgs.localCursorLastClickedPosition: the position of the last click on the grid in local grid coordinates. Use tgs.transform.TransformPoint(x) method to convert to world space coordinates.

Path Finding & LOS related

tgs.CellGetSideBlocksLOS(cellIndex, side, blocks): returns whether a cell’s side blocks line of sight.

tgs.CellSetSideBlocksLOS(cellIndex, side, blocks): specify whether a cell’s side blocks line of sight.

tgs.CellSetCanCross: specifies if this cell blocks any path.

tgs.CellSetCrossCost: specifies the cost to enter a cell (defaults to 1).

tgs.CellSetSideCrossCost: specifies the cost to enter or exit a cell through a specific edge.

tgs.FindPath(cellIndexStart, cellIndexEnd): returns a list of cell indices that form the path.

tgs.FindPath(cellIndexStart, cellIndexEnd, out totalCost, maxSearchCost, maxSteps): returns a list of cell indices that form the path and the totalCost for the path. Optionally pass a maxCost and maxSteps (use OnCellCross event to return custom costs for any cell).

tgs.FindPath(cellIndexStart, int cellIndexEnd, List<int> cellIndices, out float totalCost, float maxSearchCost = 0, int maxSteps = 0, int cellGroupMask = -1, CanCrossCheckType canCrossCheckType = CanCrossCheckType.Default, bool ignoreCellCosts = false, bool includeInvisibleCells = true, int minClearance = 1): returns a list of cell indices that form the optimal path between two cells with extra parameters:

  • cellGroupMask: bitwise mask to filter which cells can be included in the path based on their group value (set any cell group value using CellSetGroup method).

  • canCrossCheckType: specifies how “canCross” flag of each cell should be used. This parameter let you include or exclude start or end cells that has canCross disabled. A cell can be set to “block” by using CellSetCanCross method. New option added: ignoreCanCrossCheckOnAllCellsExceptStartAndEndCells. ignoreCanCrossCheckOnAllCells will ignore start and end cells.

  • ignoreCellCosts: ignores any custom cost assigned to a cell.

  • includeInvisibleCells: if hidden cell can be used in the path.

  • minClearance: determines the minimum width of the path so the unit can pass through it (eg. a unit occupies 2 square cells instead of 1). Defaults to 1. Uses true clearance algorithm.

tgs.CellGetLineOfSight(startPosition, endPosition, …): returns true or false if there’s a line of sight from the starting cell to target cell. It also returns the list of cells in the line as well as the world positions.

tgs.CellGetLine(startPosition, endPosition, …): returns a list of cells that form a line between two cells with options.

tgs.CellTestLineOfSight(startIndex, indices, …): removes any cell index from the indices list that are not visible from the given starting cell.

Other useful instance methods

tgs.instance: reference to the actual Terrain Grid System component on the scene.

tgs.HideAll: hides all surfaces (territories and cells). Surfaces are cached and kept in memory once they’re generated.

tgs.ShowAll: shows all surfaces. See HideAll() method above.

tgs.ClearAll: hides all surfaces and also clears the internal cache (surfaces are destroyed and memory freed, and will need to be generated again if a cell/territory is colored/textured).

tgs.Redraw: forces a redraw of the grid mesh. Optionally set the parameter reuseTerrainData to true to speed up computation if terrain has not changed.

tgs.RedrawCells(List<Cell>): forces a redraw of specific cells. This is faster than redrawing the entire grid when only a subset of cells is required.

tgs.CancelAnimations: similar to CellCancelAnimations or TerritoryCancelAnimations but stops any animation over the grid (flash, blink, fadeout, color temp, etc.).

Other useful static methods

TerrainGridSystem.grids: list that contains all grids in the scene.

TerrainGridSystem.GetGridAt(position): returns the grid that contains a given position.

Events

Note: in order to support multi-grid setups, all events receive the reference to the grid as the first parameter so you always know which grid is triggering the event. For example:

// OnCellClick occurs when user presses and releases the mouse button as in a normal click
tgs.OnCellClick += OnCellClick;
...
void OnCellClick (TerrainGridSystem grid, int cellIndex, int buttonIndex) {
if (buttonIndex == 0) {
   AddMessage("Mouse CLICK on cell #" + cellIndex + ", Merging!");
} else if (buttonIndex == 1) {
   AddMessage("Right clicked on cell #" + cellIndex); }
}

List of events:

tgs.OnCellEnter: triggered when pointer enters a cell.

tgs.OnCellExit: triggered when pointer exits a cell.

tgs.OnCellMouseDown: triggered when user presses mouse button on a cell.

tgs.OnCellMouseUp: triggered when user releases mouse button on a cell.

tgs.OnCellClick: triggered when user presses and releases the mouse pointer on the same cell.

tgs.OnCellHighlight: triggered when a cell is goint to be highlighted (usually when pointer is over it). A ref parameter allows you to cancel highlight and implement your own coloring system.

tgs.OnCellDragStart: triggered when user starts dragging on a cell.

tgs.OnCellDrag: triggered while user drags.

tgs.OnCellDragEnd: triggered while user released the left button while dragging.

tgs.OnTerritoryEnter: triggered when pointer enters a territory.

tgs.OnTerritoryExit: triggered when pointer exits a territory.

tgs.OnTerritoryMouseDown: triggered when user presses mouse button on a territory.

tgs.OnTerritoryMouseUp: triggered when user releases mouse button on a territory.

tgs.OnTerritoryClick: triggered when user presses and releases mouse button on the same territory.

tgs.OnTerritoryHighlight: triggered when a territory is goint to be highlighted (usually when pointer is over it). A ref parameter allows you to cancel highlight and implement your own coloring system.

tgs.OnPathFindingCrossCell: triggered when path finding algorithm estimates cost to this cell. You can use this event to return extra cost and customize path results.

tgs.OnRectangleSelection: triggered when user completes a rectangle selection. Read “Rectangle Selections” section for details.

tgs.OnRectangleDrag: triggered when user drags a rectangle selection. Read “Rectangle Selections” section for details.

Handling cells and territories

Please, refer to demo scripts included in demo scenes for example of API usage, like selecting, merging and toggling cells visibility, …

Rectangle Selection

Demo scene 20 showcases how to use the OnRectangleSelection event.

Firstly, to enable rectangle selection you must call tgs.enableRectangleSelection = true. At this point, user will be able to click and drag a rectangle. When the user drags a selection, the even OnRectangleDrag fites. And when he/she completes the rectangle selection (by releasing the mouse button), the event OnRectangleSelection is fired:

The following code corresponds to demo scene 20. It allows the user to select a rectangle of cells and color them in red:

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

public class Demo20 : MonoBehaviour {

    TerrainGridSystem tgs;

    void Start() {
        tgs = TerrainGridSystem.instance;
        tgs.enableRectangleSelection = true;
        tgs.OnRectangleSelection += SelectCells;
        tgs.OnRectangleDrag += HighlightRectangleArea;

        tgs.OnCellClick += (grid, cellIndex, buttonIndex) => PaintCell(cellIndex);
    }

    void PaintCell(int cellIndex) {
        tgs.CellSetColor(cellIndex, Color.red);
    }

    void SelectCells(TerrainGridSystem grid, Vector2 localPosStart, Vector2 localPosEnd) {
        List<int> cells = new List<int>();
        tgs.CellGetInArea(localPosStart, localPosEnd, cells);

        // Hides all surfaces (and clear cache)
        tgs.ClearAll();

        // Color selection
        tgs.CellSetColor(cells, Color.yellow);
    }

    void HighlightRectangleArea(TerrainGridSystem grid, Vector2 localPosStart, Vector2 localPosEnd) {
        List<int> cells = new List<int>();
        tgs.CellGetInArea(localPosStart, localPosEnd, cells);

        // Hides all surfaces (but keep them in cache)
        tgs.HideAll();

        // Color current selection
        tgs.CellSetColor(cells, new Color(0, 0, 1, 0.25f));
    }

}

Moving gameobjects utility methods

Demo 28 showcases a set of helper methods to place and move pieces over a grid easily. The methods are:

MoveTo(GameObject o, int row, int column, float velocity = 0, float elevation = 0): moves a gameobject to the cell specified by row/column with custom velocity and elevation. A velocity value of 0 moves the gameobject instantly.

MoveTo(GameObject o, int cellIndex, float velocity = 0, float elevation = 0): moves a gameobject to the cell specified by cell index with custom velocity and elevation. A velocity value of 0 moves the gameobject instantly.

MoveTo(GameObject o, List<int> positions, float velocity = 0, float elevation = 0): moves a gameobject along a sequence of cells with custom velocity and elevation. The positions list include the indices of the cells that form the path. You can use the FindPath method to obtain a list of indices which you can pass to this method to make a gameobject follow that path.

– MovePause(GameObject o): pauses the movement of a gameobject.

– MovePauseToggle(GameObject o): pauses or resumes the movement of a gameobject.

– MoveResume(GameObject o): resumes the movement of a gameobject.

– MoveCancel(GameObject o): stops a gameobject.

Custom user data

There are 3 ways you can add custom data to cells and territories:

Option 1

Using the attrib property. Every cell or territory object has an “attrib” property which is a JSON object that can store any number of custom fields.

For example, you coud use:

tgs.cells[10].attrib[“resource”] = “coal”;

This will store the word “coal” associated to the key “resource” of cell with index 10.

Option 2

Using the tag property. Each cell has a “tag” property which is a basic integer. You can use this field for any purpose like storing the id of some other object that’s managed by you.

Option 3

Extending the cell or territory class. Both classes are defined with the C# partial keyword which allows you to add custom fields or methods in another file. The compiler will simply merge the contents of both files when compiling the class. The benefit of adding your custom fields/properties in a different file is that it doesn’t get overwritten when you upgrade to a newer version of the asset.

Back To Top