- Home /
IndexOutofRangeException
I have been receiving a rather confusing Array Index out of bounds exception. The following code shows where I initialize the array. The problem I am having is with the "players" array.
var tilePrefab: GameObject;
var unitPrefab: GameObject;
var enemyPrefab: GameObject;
var mapSize: int = 4;
static var playerTurn: boolean;
static var turnCount: int = 0;
private var map: GameObject[,];
var players: GameObject[];
var playerCount: int =4;
function Start () {
createMap();
playerCount = 4;
players = new GameObject[4];
//players = new GameObject[playerCount];
generatePlayers();
Debug.Log("hi " + players[0]);
}
When I try to access the array during the following function I get an the out of bounds exception. However, if I try to access the array in the start function it works fine. the Debug.Log i put in the start function for testing works just fine without giving me any errors
function moveCurrentUnit(tile: Tile)
{
var dest: Vector3;
dest = tile.getLocation();
//players[turnCount].GetComponent(Unit).destination = dest;
Debug.Log("hi " + players[0]);
players[0].GetComponent(Unit).destination = dest;
if (turnCount < playerCount - 1)
{
turnCount++;
}
else if (turnCount >= playerCount - 1)
{
turnCount = 0;
}
}
additionally when I use another function to access the map array it works fine as well
function createMap()
{
map = new GameObject[mapSize, mapSize];
for(var i = 0; i < mapSize; i++)
{
for(var j = 0; j < mapSize; j++)
{
map[i,j] = newTile(i,j);
}
}
}
I have no idea what could be causing this problem. What is the difference between the way I try to access map array and the players array other than the fact that map is 2 dimensional? I even tried making the players array 2 dimensional to see if that made any difference. I'm pretty stumped any help would be appreciated
Is moveCurrentUnit called directly or indirectly by another component? If so, could it be calling the function before this Start() is called. What happens if you move the logic to Awake() ins$$anonymous$$d of Start()?
the $$anonymous$$oveCurrentUnit function is activated by a mouse click, The error only pops up when I click so I doubt that it could be getting called before the start function is. when i move the logic from start to awake I get an error at the same place, but ins$$anonymous$$d of only getting it when I click it happens every frame. from looking at it after that I realized that I am also accessing the players array in my update function, for some reason it only fails when I call moveCurrentUnit
Answer by tw1st3d · Aug 05, 2013 at 01:12 AM
private var map: GameObject[,];
fairly certain the , is causing it.
the problem I am having is with the players array, not the map array