250 000 Hexes

250000hexes_banner

This stress test shows how to create a grid that contains 250 000 hexes in Unity.

Instantiation of the game objects is the bottleneck, so objects are instantiated 1000 at at time in a co-routine.

  • Use the arrows to move around the map.
  • Use the mouse to toggle hexes on or off.

[unity src=”2602″]

Code

using UnityEngine;
using System.Collections;

using System.Linq;
using Gamelogic;
using Gamelogic.Grids;

public class StressTest : GLMonoBehaviour 
{
   public Block cellPrefab;
   public int cellsPerIteration = 1000;
   public Camera cam;
   public int width = 500;
   public int height = 500;
   public int totalCellCount;

   private PointyHexGrid grid;
   private IMap3D map;

   public void Start()
   {
      StartCoroutine(BuildGrid());
   }

   public void OnGUI()
   {
      GUILayout.TextField("Hexes: " + totalCellCount);
   }

   public void Update()
   {      
      if(Input.GetMouseButtonDown(0))
      {         
         Vector3 worldPosition = ExampleUtils.ScreenToWorld(Input.mousePosition);
         PointyHexPoint hexPoint = map[worldPosition];

         if(grid.Contains(hexPoint))
         {
            if(grid[hexPoint] != null) //may be null while grid is being built
            {
               grid[hexPoint].gameObject.active = !grid[hexPoint].gameObject.active;
            }
         }
      }   

      if(Input.GetKey(KeyCode.UpArrow))
      {
         cam.transform.position = cam.transform.position + Vector3.up * .1f;
      }

      if(Input.GetKey(KeyCode.DownArrow))
      {
         cam.transform.position = cam.transform.position + Vector3.down * .1f;
      }

      if(Input.GetKey(KeyCode.LeftArrow))
      {
         cam.transform.position = cam.transform.position + Vector3.left * .1f;
      }

      if(Input.GetKey(KeyCode.RightArrow))
      {
         cam.transform.position = cam.transform.position + Vector3.right * .1f;
      }
   }

   public IEnumerator BuildGrid()
   {   
      totalCellCount = 0;
      grid = PointyHexGrid.Rectangle(width, height);

      map = new PointyHexMap(new Vector2(69, 80))
         .Scale(0.004f)//scale factor because of mesh size from SketchUp
         .To3DXY();

      int cellCount = 0;

      var shuffledGrid = grid.ToList();
      shuffledGrid.Shuffle();

      foreach(var point in grid)
      {
         var cell = Instantiate(cellPrefab);         
         Vector3 worldPoint = map[point];

         cell.transform.localPosition = worldPoint;

         cellCount++;
         totalCellCount++;

         grid[point] = cell;

         if(cellCount >= cellsPerIteration)
         {
            cellCount = 0;
            yield return null;
         }
      }
   }
}

Leave a Reply

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

Scroll to Top