- Home /
Nested If Addition Going wrong somewhere?
I have nested if's in side a for loop which is used to add an item to a list. But when i first add an item with an amount of 4 an then add a second item with 3 it should make 7, but come out with 6?
I tried putting 'print()' functions around the function, but i couldnt see anything wrong?
Code:
public void AddItem(Item newItem){
int itemAmount = newItem.currentStack;
if(PlayerInventory.Inventory.Count > 0){
foreach(Item item in PlayerInventory.Inventory){
if(item.ID == newItem.ID){
if(item.currentStack < item.maxStack){
int availableSpace = item.maxStack - item.currentStack;
if(itemAmount <= availableSpace){
print (item.currentStack + itemAmount + " :Final Amount");
item.currentStack += itemAmount;
itemAmount = 0;
} else{
item.currentStack = item.maxStack;
itemAmount -= availableSpace;
}
}
}
}
if(itemAmount > 0){
newItem.currentStack = itemAmount;
PlayerInventory.Inventory.Add(newItem);
}
} else{
PlayerInventory.Inventory.Add(newItem);
}
print ("-------------------------");
}
try to use a
Dictionary<int,Item>
that maps your item.ID to an Item object.. that way you don't need to loop through the list.
I can help you later if you don't get it fixed or no one else helps.
I wanna stick to lists as they seem easier to handle(I was also using a dictionary earlier for a list of 'preset' items, but it wouldn't work for what i wanted to do). As with my problem i do not know what is wrong, its like unity is adding the new amount to the current stack wrong because i have checked and the function keeps the right numbers up to the addition?
Can you show the code for Item and PlayerInventory for some context?
And where you initialize and add items.
I'm a bit confused by your code. At first you assign the value of newItem.currentStack
int itemAmount = newItem.currentStack;
and then you check if the current item of the loop is equal to the new item
if(item.ID == newItem.ID){...
So within this condition item is equal to newItem and item.currentStack is equal to itemAmount
print (item.currentStack + itemAmount + " :Final Amount");
That would result in 6 if you chop a tree with amountGiven = 3 and result in 8 if the amountGiven of rock is 4.
$$anonymous$$ay be you want to add something like previousItem.currentStack to itemAmount?
@edit: nvm, I mixed up PlayerInventory.Inventory and PlayerInventory.ItemDictionary
Answer by HappyMoo · Jan 03, 2014 at 07:59 PM
Hi,
the answers site limits the length of what I can say here, so I took this to the forums.
Please have a look here: http://forum.unity3d.com/threads/220674
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Add Object to List of GameObjects C# 1 Answer
Cant instantiate from one list to another? 2 Answers
How to add item to Script Written in C# ? 1 Answer
List or Array for Rays 1 Answer