- Home /
for loop in OnInpectorGUI giving NullReferenceException error for some reason?
Hello, I am working on a custom Editor inspector for my NPC system and it seems like any time I want to display a list of items with a for loop it gives me this error:
NullReferenceException: Object reference not set to an instance of an object NPCSystemEditor.OnInspectorGUI()
It leads to my for loop. The editor still works and all but it gives me thousands of these errors, I guess because it gives me one every time OnInspectorGUI() goes.
if (GUILayout.Button("Add Dialogue Text"))
{
myNPCSystem.textsSimpleDialogue.Add(null);
}
for (int i = 0; i < myNPCSystem.textsSimpleDialogue.Count; i++)
{
GUILayout.BeginHorizontal();
myNPCSystem.textsSimpleDialogue[i] = (TextAsset)EditorGUILayout.ObjectField("Dialogue Text " + i, myNPCSystem.textsSimpleDialogue[i], typeof(TextAsset), true);
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Remove"))
{
myNPCSystem.textsSimpleDialogue.RemoveAt(i);
return;
}
GUI.backgroundColor = originalColor;
GUILayout.EndHorizontal();
}
It would be easier if you could put informationon which line error occurs.
It happens on the for loop line. for (int i = 0; i < myNPCSystem.textsSimpleDialogue.Count; i++)
then myNPCSystem or textsSimpleDialogue must be null, check where you define them. or put the for inside an if and check if any of those two have been defined yet
Answer by Master_Davicous · Apr 04, 2018 at 12:21 AM
Thanks to @Rygaran for helping me figure out this problem. When you want to present a List in a custom inspector GUI, make sure you make your List in your base class like this:
List〈T〉 listOfSomething = new List〈T〉();
This will fix the problem of the NullReferenceException error!
Your answer
![](https://koobas.hobune.stream/wayback/20220612155833im_/https://answers.unity.com/themes/thub/images/avi.jpg)