Apress / Devel-2D-Games-Unity

Source Code for 'Developing 2D Games with Unity: Independent Game Programming with C#' by Jared Halpern
https://www.apress.com/us/book/9781484237717
Other
215 stars 53 forks source link

Chapter 6 AddItem Method Why are we only filling first slot? Why don't we use the other 4 slots? #42

Closed ladinsmoor closed 3 years ago

ladinsmoor commented 3 years ago

The first time the AddItem method is called after colliding with a Coin, all of the items[i] elements are null so it jumps to the 2nd if block, and fills items[0]. Then after that, it just keeps falling into the first if block because items[0] != null. What is the purpose of the other 4 slots? Note this code below was copied and pasted from Github, with the insides of the if blocks removed, so I didn't add any extra return statements.

public bool AddItem(Item itemToAdd)
{
    for (int i = 0; i < items.Length; i++)
    {
        if (items[i] != null && items[i].itemType == itemToAdd.itemType && itemToAdd.stackable == true)
        {
            //this runs the second, and every other time the method is called because the 0th element in the items array
           // is not null. 
          //it exits with a return true statement

        }

        if (items[i] == null)
        {
           //this runs the first time this method is called, and never runs again.
           //it exits with a return true statement
        }
    }
    return false;
}
graceyh24 commented 3 years ago

As of now, only the first slot is being filled because there is only one type of consumable object: coin. However, if you look at the if statement, if (items[i] != null && items[i].itemType == itemToAdd.itemType && itemToAdd.stackable == true), other item types that you may add in the future will not just keep falling into the first if block. This is because the if statement above not only checks if the 0th item is not null; it also checks if the new itemToAdd can be stacked with the existing item in the 0th slot. If the new itemToAdd is not the same type as the existing 0th slot item, then the code will move on to the next slot by incrementing i and checking if items[1] is not null, and so on. Hope this helps!

JaredHalpern commented 3 years ago

Thank you @graceyh24! Closing this issue.