Alternative – combining all the responsibilities into a single script

The separation of the player inventory (what they are carrying) and how to display the inventory to the user is an example of a game design pattern (best practice approach) called the Model-View-Controller (MVC) whereby we separate 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 to update 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's development, if we want our final game architecture to be well structured and maintainable.

However, for very simple games we may choose to combine both status and display of that status in a single script class. For an example of this approach for this recipe, remove script components PlayerInventory and PlayerInventoryDisplay and create the following C# script class PlayerInventoryCombined and add an instance to GameObject player-SpaceGirl in the Hierarchy:

using UnityEngine.UI; 
public class PlayerInventoryCombined : MonoBehaviour { 
   public Text starText; 
   private bool carryingStar = false; 

   void Start() { 
         UpdateStarText(); 
   } 

   void OnTriggerEnter2D(Collider2D hit) { 
         if (hit.CompareTag("Star")){ 
               carryingStar = true; 
               UpdateStarText(); 
               Destroy(hit.gameObject); 
         } 
   } 

   private void UpdateStarText() { 
         string starMessage = "no star :-("; 
         if (carryingStar) 
            starMessage = "Carrying star :-)"; 
         starText.text = starMessage; 
   } 
} 
There is no difference in the experience of the player, and the change is simply in the architectural structure of our game code.