The question is answered, right answer was accepted
How do I get my Inventory Loading to work again? ArgumentOutOfRangeException
My problem is that I get an ArgumentOutOfRangeException when I go to reopen my inventory after saving. The items don't show up and I get this error.
My Code
private List<Item> inventory = new List<Item>();
void Start ()
{
LoadInventory();
StartCoroutine(Saving());
}
IEnumerator Saving()
{
while(true)
{
SaveInventory();
yield return new WaitForSeconds(5);
}
}
void SaveInventory ()
{
for (int i = 0; i < inventory.Count; i++)
{
PlayerPrefs.SetInt("Inventory " + i, inventory[i].itemID);
}
}
void LoadInventory ()
{
for (int i = 0; i < inventory.Count; i++)
{
inventory[i] = PlayerPrefs.GetInt("Inventory " + i, -1) >= 0 ? database.items[PlayerPrefs.GetInt("Inventory " + i)] : new Item();
}
}
So I keep getting an:
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index System.Collections.Generic.List`1[Item].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633) Inventory.LoadInventory () (at Assets/Scripts/Items/Inventory.cs:899) Inventory.Start () (at Assets/Scripts/Items/Inventory.cs:79)
I figure its inventory[i] = PlayerPrefs.GetInt("Inventory " + i, -1) >= 0 ? database.items[PlayerPrefs.GetInt("Inventory " + i)] : new Item();
Doesn't make since because I had it saving when I first made it. Now it just won't load the saved items. I put a print(i);
before it and it returned 12
.
Edit:: I added a debug back and it returns 12 not 0 like I had said before.
Also, if I hookup a GUI to save and load in-game, it works, but if I turn it off and turn it back on again, it will give me this error.
Answer by ThePokedog1 · Oct 08, 2015 at 11:01 PM
Not completely sure what got it to work, but after I was messing around with a different portion my game I got it to work. It was most likely that I had way to many GameObject.Find("")s. I was watching the beginning of https://www.youtube.com/watch?v=kgr6UnyKWd8 when I changed most of my databases and scripts unto a single object so that I can avoid the GameObject.Find("")s all together. Now I don't have the problem so all good!
Answer by etopsirhc · Oct 08, 2015 at 01:13 AM
my best guess would be because you are adding items to an empty inventory by index when nothing has been added to expand the inventory to it's normal size.
when you instantiate the inventory set a capacity, i think that will let you access it how you want, if not, try inventory.Insert(index,item);