C# instantiate into list

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) );
      } 
}

2 Answers

2

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));
      } 
}

Cast operation is already perform prefixing "Instantiate" with "(GameObject)". Thus "as GameObject" isn't needed.

Oops I didn't even see that. I'm so used to doing it the other way lol

initializing my list solved the problem. Speedything is also correct that you need to use "using System.Collections.Generic;". You don't need to pass it through a temp gameobject before adding to the list though. Thanks guys!

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.

That won't work as you haven't initialised your list. And you won't get a null reference exception for missing a namespace declaration

Sorry, I left that bit of code out... Edited the answer