# Unity for loop: (List) Argument out of range

I am attempting to copy the contents of one list into another. On the first iteration I get an "Argument out of range" error.

static List<Building> SaveBuildings(List<Building> buildings)
{
if (buildings.Count == 0)
return null;
Debug.Log("Save Buildings Count: " + buildings.Count);
List<Building> records = new List<Building>();
for (int i = 1; i < buildings.Count; i++)
{
Debug.Log("i: " + buildings[i].name);
records[i] = buildings[i].GetRecord();
}
return records;
}


The offending line is: records[i] = buildings[i].GetRecord();

This code "Debug.Log("Save Buildings Count: " + buildings.Count);" shows that the list is not empty. The following code "List records = new List();" instantiates a new list to be used.

My understanding is that everything should work well, but when I run the code this line fires "Debug.Log("i: " + buildings[i].name);" and then the error.

I've changed "int i" to be "0" and "i < buildings.Count" to "i <= buildings.Count" with i being 1 and 0. Same results.

I need fresh eyes to find the error lol thank you for your help

• Why do you need two IEnumerable<Building>? I obviously can't see the rest of your code and so don't know what you are doing with it but this seems to be a waste of cycles since you can just LINQ through the original collection to reference GetRecord and use anonymous objects... maybe I am missing something. – Slagmoth Apr 13 '18 at 13:28
• Thank you! I was running into a saving issue, but your question made me think about what I was doing lol. I was trying to save an array from a list to a binary file. I couldn't save the "Building" class as it derived from MonoBehaviour, so I needed to create another class that didn't derive from it and could transfer the lists between each other. – Anon Apr 13 '18 at 15:32
• Ok, that makes more sense, and if it is doing a specific function then it should be encapsolated. I guess I have some reading to do on saving game states then, I am still fairly new to Unity but am a dev irl. – Slagmoth Apr 13 '18 at 16:43

The issue is that records is empty. Are you intentionally skipping the first building? If not, I think this is what you want:
for (int i = 0; i < buildings.Count; i++)