C# array index is out of range, but is never set to be out of range [Fixed]
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ChunkCore : MonoBehaviour {
public string[,] ChunkBlocks = new string[961,32];
// Use this for initialization
void Start () {
}
public void SaveChunk(){
string SaveBlocks = "";
int SortTrys = 0;
while (SortTrys < 31) {
int setChunkDat = 0;
while (setChunkDat < 961) {
SaveBlocks += ChunkBlocks[SortTrys,setChunkDat] + ",";
setChunkDat += 1;
}
SaveBlocks += "-";
SortTrys += 1;
//end setting chunk
}
try { System.IO.File.WriteAllText( Core.StaticWorldSaveLocation + @"\Dem\Soul\Land\" + transform.name + ".dat", SaveBlocks);}
catch{Debug.Log("Error: Failed to save chunk " + transform.name);
}
}
// Update is called once per frame
void Update () {
}
}
When I run my game, and do the SaveChunk(), I get this message
IndexOutOfRangeException: Array index is out of range. ChunkCore.SaveChunk () (at Assets/Standard Assets/Scrips/WorldBuilder/ChunkCore.cs:30) CubeCore.Start () (at Assets/Standard Assets/Scrips/Cube/CubeCore.cs:40)
I changed public string[,] ChunkBlocks = new string[961,32]; to public string[,] ChunkBlocks = new string[9610,320]; and public string[,] ChunkBlocks = new string[961,31];
but still this message.
so, every now and then I miss a small thing, and then I spend hours trying to fix my "problem..."
This time I got SortTrys,setChunkDat backwards in my chunkBlocks[]. It should be
notSaveBlocks += ChunkBlocks[setChunkDat,SortTrys] + ",";
SaveBlocks += ChunkBlocks[SortTrys,setChunkDat] + ",";
If Unity says it's out of range, then it's out of range. There's no point arguing with it. ;) Ins$$anonymous$$d do dome basic debugging such as printing out the actual variable values involved, so you know what the numbers are, not just what you think they should be.
Don't edit your question and include the solution in the question. Post an answer and accept it to close the question.
Answer by Hez · Nov 08, 2015 at 03:18 AM
so, every now and then I miss a small thing, and then I spend hours trying to fix my "problem..."
This time I got SortTrys,setChunkDat backwards in my chunkBlocks[]. It should be
notSaveBlocks += ChunkBlocks[setChunkDat,SortTrys] + ",";
SaveBlocks += ChunkBlocks[SortTrys,setChunkDat] + ",";
I put the big number where the little number should be, and the little number where the big number should be...
Your answer
![](https://koobas.hobune.stream/wayback/20220612044318im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[C#] Error in script [IndexOutOfRangeException] 1 Answer
array index out of range 1 Answer
Array out of index, but shouldn't be 2 Answers
IndexOutOfRangeException: Array index is out of range?? 0 Answers