- Home /
Convert Object[] to List
I had an inventory script working with Object[], but now it needs to be more dynamic, and needs to combine more Resources.LoadAll() folders. It seemed pretty straight forward, so I tried this:
public static List<Object> inventory;
//import all blocks
Object[] allBlocks = Resources.LoadAll ("Prefabs/Blocks");
Debug.Log ("AllBlocks[0]: "+allBlocks[0]); //Prints successfully
//convert object[] to list<object>
for (int i = 0; i<allBlocks.Length; i++){
inventory.Add(allBlocks[i]); //throws NullReferenceException
}
Debug.Log ("Inventory[0]: "+inventory[0]);
I'm getting a NullReferenceException when I try to put Object[0] into List[0], even though Debug.Log(Object[0]) prints out the name of the prefab.
Answer by Jeff-Kesselman · Jun 04, 2014 at 08:52 PM
You forget to create your list. Change
public static List<Object> inventory;
to
public static List<Object> inventory = new List<Object>();
Answer by rutter · Jun 04, 2014 at 08:53 PM
You must create the list before you can use it:
inventory = new List<Object>();
Of course, List
also has a constructor that will populate the list for you:
inventory = new List<Object>(allBlocks);
Or you can add several items at once:
inventory.AddRange(allBlocks);
Answer by Millimedia_Games · Sep 25, 2019 at 11:30 AM
The title of this says Object[] (array) to list. this is List to an array or am I miss-reading?