Odd NullReferenceException on FOR loop
For loop throws NullReferenceException, my asumption is because of array index not tolerated BUT I tested index in the same loop to make sure it is valid and it IS valid.
I am puzzled, please help.
TER_Block nBlock = NewGO.AddComponent<TER_Block>();
nBlock.Points = ChunkPoints;
if (ChunkDirections.Count > 1)
{
for (int i = 0; i < ChunkDirections.Count; i += 2)
{
Debug.Log("Count = " + ChunkDirections.Count + " / i = " + i + " / " + ChunkDirections[i] + " / " + ChunkDirections[i + 1]);
if (isRight) nBlock.Directions.Add(ChunkDirections[i]);
else nBlock.Directions.Add(ChunkDirections[i + 1]);
}
}
// LOG output :
// ...
// Count = 4 / i = 0 / (1.0, 0.0, 0.0) / (-1.0, 0.0, 0.0)
// NullReferenceException: Object reference not set to an instance of an object [...] at MNG_Terrain.cs : 660
// Count = 6 / i = 0 / (1.0, 0.0, 0.0) / (-1.0, 0.0, 0.0)
// NullReferenceException: Object reference not set to an instance of an object [...] at MNG_Terrain.cs : 660
// ...
Line 660 of MNG_Terrain is the following bit : else nBlock.Directions.Add(ChunkDirections[i + 1]); .
Values are ALWAYS added by pair to the ChunkDirections list (right and left vector3 s).
As proven by Debug.Log, values for both i = 0 and i = 1 are in ChunkDirections list, but despite this, else statement throws an NRE.
If I delete the ELSE statement, suddenly the error gets thrown on line 659; the line where I use i as an index.
nBlock.Directions absolutely exists, it is used all around the FOR loop without issues, and no variables are static.
please HELP
For now I circumvent the issue by creating a new list before the loop and adding values to it through the loop, then copy that list over to the nBlock.Directions list after the loop ended. It works but I am really frustrated at why it doesn't work directly in the loop, I really don't see why. Could someone help please.
I forgot to specify that I tested nBlock inside of the loop with other calls (printing its name in a debug log) and it worked fine.
Your answer
Follow this Question
Related Questions
Getting array from Json suddenly doesnt work. 1 Answer
Named array assigned to new array, named array returns null on all subsequent calls 0 Answers
Can't access public static array from another class 1 Answer
[SOLVED] Remove Vector3 Array step by step when GameObject spawned 1 Answer
index out of range problem with for loops and arrays. 1 Answer