Why use Inventory.GetPlayerInventory() instead of GetComponent<Inventory>()?

Just like the title states, why is playerInventory = Inventory.GetPlayerInventory() used as an extra function in Inventory.cs rather than getting the player and the component Inventory on the player in InventoryItemIcon.cs?

In my own opinion it’s cleaner and less prone to mistakes. It also does what you want without the need to know where to find any of these things. I don’t have to know where the player inventory lives. I just know I want the player’s inventory, so I ask the Inventory class to give me the player’s inventory. If I change where the player’s inventory lives, I can update one place and all references will still be good. If I had to get the player and then get the inventory from there, I’d have to update everywhere I did that.

Remember that all of the UI code is NOT on the Player… meaning that it has no inherent link to the player. Inventory.GetPlayerInventory() is just a convenient way of avoiding a WET solution (We Enjoy Typing) for each of the classes that rely on the Player’s inventory. It’s a bit of shorthand for

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms