0
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Slagmoth Apr 13 '18 at 13:28
  • \$\begingroup\$ 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. \$\endgroup\$ – Anon Apr 13 '18 at 15:32
  • \$\begingroup\$ 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. \$\endgroup\$ – Slagmoth Apr 13 '18 at 16:43
3
\$\begingroup\$

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++)
{
    records.Add(buildings[i].GetRecord());
}   
\$\endgroup\$
  • \$\begingroup\$ OMG records is a list....lol I knew I wouldn't be able to solve it cause in my mind I was doing everything right so I couldn't see the errors lol. Thank you so much! \$\endgroup\$ – Anon Apr 13 '18 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.