- Home /
Null Reference Exception Unless Scripted Object is Selected
Hi everyone, I have found an odd little glitch in one of my scripts.For some reason when I startup my script unity keeps giving me a null reference exception unless I select the object that the script is attached to.Why is it doing this and how do I fix this?
Can you post the relevant code? It's a bit difficult to diagnose without it (as an example, do you make use of the OnEnable function?).
I don't know why but it keeps saying that the BoolList[i].BoolValue = true; is causing the null reference.
[System.Serializable]
public class BoolValueClass
{
public bool BoolValue = false;
}
public List BoolList;
Void OnGUI(){
for (int i = 0; i < BoolList.Count; i++)
if (GUILayout.Button("BoolButton",
GUILayout.Width(75), GUILayout.Height(25)))
{
BoolList[i].BoolValue = true;
}
}
Also the BoolList is suppose to inherit from BoolValueClass for some reason I can't copy/paste that bit in.
Answer by karl_ · Oct 01, 2012 at 04:52 AM
Based on the script, it looks like `BoolList` is not initialized, and therefore null. To avoid this, initialize BoolList in your declaration.
public List<bool> BoolList = new List<bool>();
Also, I'm not really sure what your script is trying to accomplish here. It looks like it's missing parts, but I'm assuming BoolValueClass is some sort of container you wish to create a list of. In that case, the syntax would be
public List<BoolValueClass> BoolList = new List<BoolValueClass>();
Edit: Full script showing how to work with a data class like this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class BoolValueClass
{
public bool BoolValue = false;
public BoolValueClass(bool val)
{
BoolValue = val;
}
}
public class BoolListExample : MonoBehaviour {
public List<BoolValueClass> BoolList = new List<BoolValueClass>();
void Awake()
{
// fill the boollist with some values
for(int i = 0; i < 10; i++)
{
if(i % 2 == 0)
BoolList.Add(new BoolValueClass(true));
else
BoolList.Add(new BoolValueClass(false));
}
}
void OnGUI()
{
for (int i = 0; i < BoolList.Count; i++)
{
if (GUILayout.Button("BoolButton", GUILayout.Width(75), GUILayout.Height(25)))
BoolList[i].BoolValue = true;
}
}
}
Try adding a null check before your for loop: `if(BoolList != null) for ...`
Nope, still getting a null reference exception. I've noticed that it only happens with bools. If I made BoolValue an int it would work fine.
I've updated my answer with a fully working script that demonstrates what I think you're attempting to do.
I tested your script and I didn't receive any null reference exceptions. Could you please tell me what you did in your script that fixed the null references?