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?

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*.BoolValue = true;* 
  •  }*
    
  • }*
    }