Unity 2018 Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

The big picture

The two parts of software design for implementing inventories relate to, first, how we choose to represent the data about inventory items (that is, the data types and structures to store the data) and, second, how we choose to display information about inventory items to the player (the UI).

Also, whilst not strictly inventory items, player properties such as lives left, health, and time remaining can also be designed around the same concepts that we present in this chapter.

We need to first think about the nature of different inventory items for any particular game:

  • Single items:
    • Examples: the only key for a level, our suit of magic armor
    • Data type: bool (Boolean – true/false)
    • UI: nothing (if not carried) or text/image to show being carried
      • Or perhaps, if we wish to highlight to the player that there is an option to carry this item, then we could display a text string saying no key/key, or two images, one showing an empty key outline and the second showing a full-color key.
  • Continuous item:
    • Examples: time left, health, shield strength
    • Data type: float (for example, 0.00-1.00) or int (Integer) scale
      (for example, 0% to 100%)
    • UI: text number or image progress bar/pie chart
  • Two or more of same item
    • Examples: lives left, or number of arrows or bullets left
    • Data type: int (Integer – whole numbers)
    • UI: text count or images
  • Collection of related items
    • Examples: keys of different colors to open correspondingly colored doors, potions of different strength with different titles
    • Data structure: a struct or class for the general item type (for example, class Key (color/cost/doorOpenTagString), stored as an array or List<>
    • UI: text list or list/grid arrangement of icons
  • Collection of different items
    • Examples: keys, potions, weapons, tools, all in the same inventory system
    • Data structure: List<> or Dictionary<> or array of objects, which can be instances of different class for each item type

Each of the preceding representations and UI display methods are illustrated by the recipes in this chapter. In addition, in the chapter we'll learn how to create and use custom Sorting Layers in order to have complete control over which objects appear on top of or below other objects – something that is pretty important when scene content can contain background images, pickups, player characters, and so on.

These recipes demonstrate a range of C# data representations for inventory items and a range of Unity UI interface components for displaying the status and contents of player inventories at runtime. Inventory UI needs good quality graphical assets for a high-quality result. Some sources of assets that you might wish to explore include the following sites: