- Home /
C# Array Index Out of Range
Hello.
I come from an AS3 background and the C# way of doing things is throwing me for a loop. I'm trying to create an array of transforms for a tile editor. Whenever I try to check if the transform is null I get an out of range exception. I'm guessing that I haven't initialized it, but it looks good when I compare it with the code on MSDN.
Here's the code in question. Any assistance would be greatly appreciated!
Editor.CS
void UpdateTile ()
{
if (tile == null || !inRange)
return;
if (deleting)
{
if (map.instances[index] != null)
{
DestroyImmediate (map.instances[index].gameObject);
map.instances[index] = null;
}
}
else
{
if (map.instances[index] == null)
{
var instance = Instantiate (tile) as Transform;
instance.parent = ship.transform;
instance.position = new Vector3 (cursorX * map.gSize, cursorY * map.gSize);
map.instances[index] = instance;
}
}
}
TileMap.CS
public class TileMap: MonoBehaviour
{
public float gSize = 1.0f;
public int gColumns = 6;
public int gRows = 6;
public Transform[] instances = new Transform[1000];
}
Can you post the code related to "index"? Your code looks fine relative to index, if index is < 1000. What's the exact error?
Answer by DaveA · Nov 18, 2013 at 05:22 AM
Put this:
public Transform[] instances = new Transform[1000];
into a Start routine. Can't trust out-of-function initialization.
That did it! There are a myriad of other issues with my code, but the out-of-range error is now taken care of. Thank you.
Your answer
