- Home /
Getting NullReferenceException when creating class instance using List
I'm trying to create instance of class using List instead of array and getting error , i don't know the exact cause
please let me know if there is any workaround to use List of Class objects Thanks in advance for any suggestion or code !
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable] public class BaseClass{
public int index ;
public List<GameObject> itemList;
}
public class GameLogicClass : MonoBehaviour {
public List<BaseClass> baseClassInstance;
void Start(){
for(int _m = 0;_m < 10;_m++){
baseClassInstance.Add(new BaseClass());
baseClassInstance[_m].index = 1;
}
Debug.Log(baseClassInstance[0].itemList.Count ); // < Getting ERROR here : NullReferenceException: Object reference not set to an instance of an object GameLogicClass.Start ()
}
}
Answer by Scribe · Nov 16, 2014 at 10:55 PM
I think you need to define what the list is of (though this may be optional as it sounds like you aren't getting an error here)
public List<BaseClass> baseClassInstance;
and you need to initialise the list somwhere:
void Start(){
baseClassInstance = new List<BaseClass>();
for(int _m = 0;_m < 10;_m++){
baseClassInstance.Add(new BaseClass());
baseClassInstance[_m].index = 1;
}
Debug.Log(baseClassInstance[0].itemList.Count );
}
Also in future can you highlight all your code and hit the '101010' button or press 'Ctrl+K' to format your code!
Thanks,
Scribe
Oh looks like someone beat me to doing the reformatting for you! :D
i just edited my post , could you please have a look , it went bad because of hitting login/post button before completing my question :-P
Thanks Scribe for your quick reply, I just tried your suggestion and initialised list inside Start(), however i'm still getting the same error Note: I'm able to print/overwrite "index" value , the only problem is with "itemList"
You need to initialise that as well! On my phone so sorry for any bad formatting
public List<GameObject> itemList = new List<GameObject>();
Or by doing:
baseClassInstance.Add(new BaseClass());
baseClassInstance[_m].index = 1;
baseClassInstance[_m].itemList = new List<GameObject>();
Your answer
Follow this Question
Related Questions
All Arrayinstances get changed -1 Answers
Does a new instance of a custom class return null? 2 Answers
Unable to delete object from a list using foreach loop 1 Answer
Multiple Cars not working 1 Answer