- Home /
List .add problem
OK, this one has been infuriating me. I am using many lists with no problems. I am making a list of my own class but it won't let me add an item to it. I get a runtime null reference error and I can't figure out why.
Here is my relevant code:
public class LevelDetails
{
public float TargetHue;
public int TargetCount;
public List<GameObject> InvetoryList;
public LevelDetails()
{
TargetHue = 0;
TargetCount = 0;
}
}
public class MyGameFunctions : MonoBehaviour
{
public List<LevelDetails> levelDeatails;
void Start();
{
levelDeatails.Add(new LevelDetails());
}
}
The runtime error occurs at the .add method and is:
NullReferenceException: Object reference not set to an instance of an object
I've tried removing the list inside the class thinking that it might be the cause but it didn't make a difference.
Answer by DoTA_KAMIKADzE · Nov 10, 2015 at 08:09 PM
Change your Start function to this:
void Start ()
{
levelDeatails = new List<LevelDetails>();
levelDeatails.Add(new LevelDetails());
}
or do like that:
public List<LevelDetails> levelDeatails = new List<LevelDetails>();
void Start ()
{
levelDeatails.Add(new LevelDetails());
}
also notice that you don't need ";" after Start function line.
@2-zons:
You also might want to make your custom class serializable. In that case you don't need to create the list since the inspector will create the list for you. However that only works when you add your "$$anonymous$$yGameFunctions" clas inside the editor. When you add it dynamically at runtime using AddComponent you have to initialize your list yourself.
[System.Serializable]
public class LevelDetails
{
//....
That way you can fill your list in the inspector.
Your answer
![](https://koobas.hobune.stream/wayback/20220612044632im_/https://answers.unity.com/themes/thub/images/avi.jpg)