- Home /
Why do I keep getting NullReferenceException in Unity while iterating over a List (in OnDrawGizmos)?
I have a following piece of code :
void OnDrawGizmos ()
{
Gizmos.color = new Color (1.0f, 1.0f, 0.5f, 0.5f);
for (int i = 0; i < listOfNodesToDraw_.Count; i++) {
Gizmos.DrawCube (
new Vector3 (listOfNodesToDraw_ [i].X, 1f, listOfNodesToDraw_ [i].Y),
new Vector3 (board_.TileWidth_, board_.TileWidth_ * 0.1f, board_.TileWidth_));
}
}
listOfNodesToDraw_
is a List
. After I quit my game I get this error stacking up in console :
NullReferenceException: Object reference not set to an instance of an object pathfinder_PlaneAttachedScript.OnDrawGizmos () (at Assets/Scripts/pathfinder_PlaneAttachedScript.cs:182) UnityEditor.DockArea:OnGUI()
In game everything is fine and no errors are thrown. What am I doing wrong here ?
EDIT
my OnDrawGizmos()
( the exception is at the for loop line)
void OnDrawGizmos ()
{
Gizmos.color = new Color (1.0f, 1.0f, 0.5f, 0.5f);
for (int i = 0; i < listOfNodesToDraw_.Count; i++) {
Gizmos.DrawCube (
new Vector3 (listOfNodesToDraw_ [i].X, 1f, listOfNodesToDraw_ [i].Y),
new Vector3 (board_.TileWidth_, board_.TileWidth_ * 0.1f, board_.TileWidth_));
}
}
Answer by Loius · Dec 24, 2012 at 03:08 AM
If 182 is in there somewhere, then "listOfNodesToDraw-underscore" contains a null entry, or "board-underscore" is null itself.
why can't we just have [i] and [b] like everyone else
Answer by Markus__T · Sep 08, 2015 at 09:26 AM
@lordmonkey - I know this answer is a few years late, but since I couldn't find a solution online, I figured I'd post my discovery anyway.
In OnDrawGizmos() add the line at the start of the method
if (!Application.isPlaying) return;
This seems to stop Unity from trying to update the gizmos after the program is playing