I’ve tried to solve this seemingly simple problem for hours now.
I have a dictionary called curInventory which I want to create a temporary copy of. But for some weird reason, everytime I change the temporary copy, the changes automatically gets applied to the original one as well. Here’s the code:
// check that all neccessary items exist in inventory
function CheckItems () : boolean {
// create a temporary inventory to check items
tempInventory = new Dictionary.<GameObject,int>();
tempInventory = inventory.curInventory;
// iterate through all needed recipes
for (var recipe : GameObject in recipeList){
if (tempInventory.ContainsKey(recipe) tempInventory[recipe] > 0){
// remove item from list
tempInventory[recipe] -= 1; // when I change tempInventory here, it also changes the original dictionary
}
else {
// not all items are existing, return false
return false;
}
}
// everything exists in inventory, return true
return true;
}
Is there some kind of magical rule with dictionaries that I’m missing, or have I just made a stupid error somewhere else in the code?
Probably the same issues that i’ve already tried to explain here.
You just set your variable tempInventory to reference a new object, this is almost correct. But one line later, you tell tempInventory to reference your curInventory. This does only work with data types such as int, float etc but also structs.
However, classes are reference types, so these both now reference the exact same object and both can be used in order to alter it, which you do not want in this case.