title: Unity: How to represent grid map data in ECS
body: <p>I have been trying to work with Unity's pure ECS approach to make a basic nxn grid of tiles.</p>
  
  <p>Before using ECS I would just use a 2d array <code>Tiles[,] grid</code> where I can simply index (x,y) to find the tile I want.</p>
  
  <p>Now moving into ECS, I want to create an entity for each tile using an IComponentData struct like so:</p>
  
  <pre><code>public struct Tile : IComponentData
  {
      public int xIndex;
      public int yIndex;
  
      public int isValid;
  }
  </code></pre>
  
  <p>Somewhere during the start of my game I create the tile entities</p>
  
  <pre><code>    for (int i = 0; i &lt; tilesInMap; i++)
      {
          Entity tileEntity = entityManager.CreateEntity(tileArchetype);
  
          int xIndex = i % terrainSize;
          int yIndex = i / terrainSize;
  
          entityManager.SetComponentData(tileEntity, new Position { Value = new float3(xIndex , 0, yIndex) });
  
          Tile newTile;
          newTile.xIndex = xIndex;
          newTIle.yIndex = yIndex;
          newTile.isValid = 1;
  
          entityManager.SetComponentData(tileEntity, newTile);
      }
  </code></pre>
  
  <p>Now somewhere else in my code I have a <code>ComponentSystem</code> that pulls in the tiles using a group struct</p>
  
  <pre><code>public struct TileGroup
  {
      public readonly int Length;
      public EntityArray entity;
      public ComponentDataArray&lt;Tile&gt; tile;
  }
  
  [Inject] TileGroup m_tileGroup;
  </code></pre>
  
  <p>As far as I'm aware, as long as I don't change the archetype of any of those entities in the TileGroup (for instance by calling <code>AddComponent</code> or <code>RemoveComponent</code>), the ordering of that injected array will be preserved (I'm not even sure of that!)</p>
  
  <p>So say in my <code>OnUpdate</code> method I want to "get the tile at grid coordinate (23, 43)". I can calculate this (assuming a 1d array of tiles with the order preserved) by </p>
  
  <pre><code>int arrayIndex = yIndex * tilesPerMapWidth + xIndex;
  </code></pre>
  
  <p>But this only works as long as the injected array order of tiles is preserved which I doubt it will be eventually. </p>
  
  <p>So a few questions:
  1. Should I ever rely on the order of an injected array for behaviour logic?
  2. Are there any better methods in achieving what I want using ECS?</p>