Why am I having trouble instantiating into a list? When I my script I get the following error: NullReferenceException: Object reference not set to an instance of an object. I’m using a public variable that has a game object placed in the inspector. I don’t understand why it shows as null.
public GameObject _gameObject;
List <GameObject> _list;
//--------------------------------
void Start(){
for(int i=0; i<5; i++){
_list.Add( (GameObject)Instantiate(_gameObject) );
}
}
You haven’t initialised your list yet…
void Start()
{
_list = new List<GameObject>();
for(int i=0; i<5; i++){
_list.Add( (GameObject)Instantiate(_gameObject));
}
}
Have you added the this line to the top of your code?
using System.Collections.Generic;
If you have then try changing your start code to this,
void Start() {
List<GameObject> _list = new List<GameObject>();
for(int i=0, i<5, i++) {
GameObject thisObject = Instantiate(_gameObject) as GameObject;
_list.Add(thisObject);
}
}
I’m not entirely sure what the difference is, but that code is in the format I use and always works fine.