Reputation: 23
This is for a game. I'm trying to reload the player's items back into their inventory when they load the game. "itemStrings" below is a list of strings of all the item names from when the player saved the game. Here's the code:
void Load(){ List<string> itemStrings = SaveLoad.Load<List<string>>("Inventory");
foreach(string nameString in itemStrings)
{
loadReference = itemDatabase.itemsDatabaseList.Where(obj => obj.name == nameString).First();
bool wasAdded = instance.Add(loadReference);
}}
For reference, itemDatabase is a reference to a class, ItemDatabase. that stores every item in the game. loadreference is a class called Item that's declared at the beginning of this Inventory class.
What I'm trying to do is search the database for an item whose name matches the string from itemStrings, then take that item and add it to the player's inventory. This 'foreach' works correctly for the first item in the list of itemStrings, but it only runs that one time. So it only loads one item into the inventory, no matter how many were saved previously.
Upvotes: 2
Views: 621
Reputation: 21487
I would rewrite your inner query to just return all the values in one request.
void Load()
{
var inventory = SaveLoad.Load<List<string>>("Inventory")
.Join(itemDatabase.itemDataList, name=>name, item=>item.name, (name,item)=>item);
// Use one of the following three methods:
instance.AddRange(inventory);
// or if instance is just a List of items then...
instance = inventory.ToList();
// or if there is no AddRange, and instance is not just a List:
foreach(var item in inventory)
{
instance.Add(item);
}
}
Alternatively, create yourself a GetInventory method:
IEnumerable<Item> GetInventory()
{
return SaveLoad.Load<List<string>>("Inventory")
.Join(itemDatabase.itemDataList, name=>name, item=>item.name, (name,item)=>item);
}
Then you can do whatever you want with it in your Load method.
Upvotes: 1
Reputation: 11273
This is happening because your loadReference
is defined elsewhere, so you are just changing pointers around (basically copying over the previously loaded item each time).
void Load()
{
List<string> itemStrings = SaveLoad.Load<List<string>>("Inventory");
foreach(string nameString in itemStrings)
{
var item = itemDatabase.itemsDatabaseList.Where(obj => obj.name == nameString).First();
bool wasAdded = instance.Add(item);
}
}
Upvotes: 1