Game Development Reference
In-Depth Information
Adding items
Now, we'll create our first interaction with the inventory: adding items. This is probably
the most important aspect of having an inventory. Why have an inventory that can't
have items added to it?
Let's figure this out
Before we jump into the coding, let's take a moment and plan out how we want to add
items to our inventory. From the player's point of view, adding items to their inventory
is something as simple as placing the item in their bag, or walking into the object and
having it appear in their inventory. What they do is similar to how we will add items.
They see an empty slot in their inventory and then place their newly obtained item
into that slot. We will be following a process similar to that within our code, creating
an inventory system that allows the player to pick up items off the ground.
Creating the adding function
Add the following function to your script, just below the InitializeInventory
function:
void AddToInventory(int HowMany, GameObject
NewItem)
{
for(int i = 0; i < invItems.Length; i++)
{
if(invItems[i].name != "Empty")
{
if(invItems[i].name == NewItem.name)
{
int val = itemCount[i].Value + HowMany;
itemCount[i] = new KeyValuePair<int,
int>(itemCount[i].Key, val);
break
};
}
Search WWH ::




Custom Search