
How it works...
You created a UI Text GameObject Text-carrying-star to display to the player a text message stating whether or not a star is being carried. You created two script classes, and an instance of each was added as a component to the player's player-SpaceGirl character GameObject:
- Script-class PlayerInventory detects player-star collisions, updates internal variables saying whether a star is carried, and asks for the UI display to be updated each time a collision is detected.
- Script-class PlayerInventoryDisplay handles the communication to the user by updating the text message displayed by the Text-carrying-star UI Text GameObject.
A game design pattern (best practice approach) called the Model-View-Controller pattern (MVC) separates the code that updates the UI from the code that changes player and game variables such as score and inventory item lists. Although this recipe has only one variable and one method for updating the UI, well-structured game architectures scale up to cope with more complex games, so it is often worth the effort of a little more code and an extra script class, even at this game-beginning stage, if we want our final game architecture to be well structured and maintainable.
One additional advantage of this design pattern is that the method in which the information is communicated to the user via the UI can be changed (for example, from text to an icon – see the next recipe!), without any change to the code in script class PlayerInventory.