- Home /
IndexOutOfRangeException in build but not editor
Im' having a problem where I get IndexOutOfRangeException: Array index is out of range. only when I build my project.
I'm creating an 11 by 11 array called hexTiles of type Hex (which I have defined elsewhere). This is used to store some hex tile objects that form a game board. The exception occurs when attempting to access hexTiles[1,4], but [1,4] should not be out of bounds.
When running the game from inside the Unity editor, everything works perfectly. However, when I build, most of the hex tiles don't appear in the game and output_log.txt shows the above exception.
I'm trying to figure out
Why is this happening at all?
Why does it work up until accessing hexTiles[1,4]?
Why is it not happening in the editor?
The relevant bit of the code below occurs in CreateMap(). (Note that the for loops that write to hexTiles go from -5 to 5, rather than 0 to 10 as it's more convenient given how I'm indexing the hex grid.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexMap : MonoBehaviour {
public Material[] terrainMaterials;
public GameObject hexTilePrefab;
public GameObject characterPrefab;
private Hex[,] hexTiles = new Hex[11,11];
private GameObject[,] hexTileObjects = new GameObject[11, 11];
private GameObject heroObject;
// Use this for initialization
void Start()
{
CreateMap();
SpawnPlayer();
}
public void CreateMap()
{
for (int column = -5; column < 6; column++)
{
for (int row = -5; row < 6; row++)
{
if (Mathf.Abs(column+row) <= 5)
{
Hex h = new Hex(column, row);
hexTiles[column+5, row+5] = h; // exception in build but not editor at column=-4, row=-1
GameObject hexPrefab = Instantiate(HexTilePrefab, h.Position(), Quaternion.identity, this.transform);
hexTileObjects[column + 5, row + 5] = hexPrefab;
MeshRenderer mr = hexPrefab.GetComponentInChildren<MeshRenderer>();
Material[] mats = mr.materials;
mats[1] = terrainMaterials[Random.Range(0, terrainMaterials.Length)];
mr.materials = mats;
hexPrefab.GetComponentInChildren<HexObjectData>().coords = new IntVector3(column,row, -(column + row ));
}
}
}
}
public Hex GetHex(int col, int row)unity
{
return new Hex(col,row);
}
public void SpawnPlayer()
{
Hero hero = new Hero(0,0);
heroObject = Instantiate(CharacterPrefab, hero.Position(), Quaternion.identity, this.transform);
}
public GameObject GetHeroObject()
{
return heroObject;
}
}
Any help much appreciated.
Your answer
![](https://koobas.hobune.stream/wayback/20220612144720im_/https://answers.unity.com/themes/thub/images/avi.jpg)