Displaying multiple pickups of different objects as a list of text via a dynamic List<> of PickUp objects

When working with different kinds of pickups, one approach is to use a C# List to maintain a flexible-length data structure of the items currently in the inventory. In this recipe, we will show you how, each time an item is picked up, a new object is added to such a List collection. An iteration through the List is how the text display of items is generated each time the inventory changes. We introduce a very simple PickUp script class, demonstrating how information about a pickup can be stored in a scripted component, extracted upon collision, and stored in our List.

Displaying multiple pickups of different objects as a list of text via a dynamic List<> of PickUp objects

Getting ready

This recipe assumes that you are starting with the project Simple2Dgame_SpaceGirl setup from the first recipe in this chapter. The font you need can be found in the 1362_02_02 folder.

How to do it...

To display inventory total text for multiple pickups of different object types, follow these steps:

  1. Start with a new copy of the mini-game Simple2Dgame_SpaceGirl.
  2. Edit the tags, changing tag Star to Pickup. Ensure that the star GameObject now has the tag Pickup.
  3. Add the following C# Script PickUp to GameObject star in the Hierarchy:
    using UnityEngine;
    using System.Collections;
    
    public class PickUp : MonoBehaviour {
      public string description;
    }
  4. In the Inspector, change the description property of component Pick Up (Script) of GameObject star to the text star, as shown in the following screenshot:
    How to do it...
  5. Select the GameObject star in the Hierarchy panel and make a copy of this GameObject, renaming the copy heart.
  6. In the Inspector, change the description property of component Pick Up (Script) of GameObject heart to the text heart. Also, drag from the Project panel (folder Sprites) image healthheart into the Sprite property of GameObject heart. The player should now see the heart image on screen for this pickup item.
  7. Select the GameObject star in the Hierarchy panel and make a copy of this GameObject, renaming the copy key.
  8. In the Inspector, change the description property of component Pick Up (Script) of GameObject key to the text key. Also, drag from the Project panel (folder Sprites) image icon_key_green_100 into the Sprite property of GameObject key. The player should now see the key image on screen for this pickup item.
  9. Make another one or two copies of each pickup GameObject and arrange them around the screen, so there are two or three each of star, heart, and key pickup GameObjects.
  10. Add the following C# Script Player to GameObject player-SpaceGirl in the Hierarchy:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using System.Collections.Generic;
    
    public class Player : MonoBehaviour {
      private PlayerInventoryDisplay playerInventoryDisplay;
      private List<PickUp> inventory = new List<PickUp>();
    
      void Start(){
        playerInventoryDisplay = GetComponent<PlayerInventoryDisplay>();
        playerInventoryDisplay.OnChangeInventory(inventory);
      }
      
      void OnTriggerEnter2D(Collider2D hit){
        if(hit.CompareTag("Pickup")){
          PickUp item = hit.GetComponent<PickUp>();
          inventory.Add( item );
          playerInventoryDisplay.OnChangeInventory(inventory);
          Destroy(hit.gameObject);
        }
      }
    }
  11. Add a UI Text object (Create | UI | Text). Rename it Text-inventory-list. Change its text to the quick brown fox jumped over the lazy dog the quick brown fox jumped over the lazy dog, or another long list of nonsense words, to test the overflow settings you change in the next step.
  12. In the Text (Script) component, ensure that Horizontal Overflow is set to Wrap, and set Vertical Overflow to Overflow—this will ensure that the text will wrap onto a second or third line (if needed) and not be hidden if there are lots of pickups.
  13. In the Inspector panel, set its font to Xolonium-Bold (folder Fonts) and set its color to yellow. For the Alignment property, center the text horizontally and ensure that the text is top aligned vertically, and set the Font Size to 28 and choose a yellow text Color.
  14. Edit its Rect Transform and set its Height to 50. Then, while holding down SHIFT and ALT (to set pivot and position), choose the top-stretch box. The text should now be positioned at the middle top of the Game panel, and its width should stretch to match that of the whole panel.
  15. Your text should now appear at the top of the game panel.
  16. Add the following C# Script PlayerInventoryDisplay to GameObject player-SpaceGirl in the Hierarchy:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using System.Collections.Generic;
    
    public class PlayerInventoryDisplay : MonoBehaviour
    {
      public Text inventoryText;
    
      public void OnChangeInventory(List<PickUp> inventory){
        // (1) clear existing display
        inventoryText.text = "";
    
        // (2) build up new set of items
        string newInventoryText = "carrying: ";
        int numItems = inventory.Count;
        for(int i = 0; i < numItems; i++){
          string description = inventory[i].description;
          newInventoryText += " [" + description+ "]";
        }
    
        if(numItems < 1) newInventoryText = "(empty inventory)";
    
        // (3) update screen display
        inventoryText.text = newInventoryText;
      }
    }
  17. From the Hierarchy view, select the GameObject player-SpaceGirl. Then, from the Inspector, access the Player Inventory Display (Script) component and populate the Inventory Text public field with the UI Text object Text-inventory-list.
  18. Play the game—each time you pick up a star or key or heart, the updated list of what you are carrying should be displayed in the form carrying: [key] [heart].

How it works...

In the script class Player, the variable inventory is a C# List<>. This is a flexible data structure, which can be sorted, searched, and dynamically (at run time, when the game is being played) have items added to and removed from it. The <PickUp> in pointy brackets means that variable inventory will contain a list of PickUp objects. For this recipe, our PickUp class just has a single field, a string description, but we'll add more sophisticated data items in PickUp classes in later recipes.

When the scene starts, the Start() method of script class Player gets a reference to the PlayerInventoryDisplay scripted component and also initializes variable inventory to be a new, empty C# List of PickUp objects. When the OnColliderEnter2D(…) method detects collisions with items tagged Pickup, the PickUp object component of the item hit is added to our inventory list. A call is also made to the OnChangeInventory(…) method of playerInventoryDisplay to update out inventory display to the player, passing the updated inventory List as a parameter.

The script class playerInventoryDisplay has a public variable, linked to the UI Text object Text-inventory-list. The OnChangeInventory(…) method first sets the UI text to empty, and then loops through the inventory list, building up a string of each items description in square brackets ([key], [heart], and so on). If there were no items in the list, then the string is set to the text (empty inventory). Finally, the text property of the UI Text object Text-inventory-list is set to the value of this string representation of what is inside variable inventory.

There's more...

Some details you don't want to miss:

Order items in the inventory list alphabetically

It would be nice to alphabetically sort the words in the inventory list—both for neatness and consistency (so, in a game, if we pick up a key and a heart, it will look the same regardless of which order), but also so that items of the same type will be listed together, so we can easily see how many of each item we are carrying.

Order items in the inventory list alphabetically

To implement the alphabetic sorting of the items in the inventory list, we need to do the following:

  1. Add the following C# code to the beginning of method OnChangeInventory(...) in the script class PlayerInventoryDisplay:
    public void OnChangeInventory(List<PickUp> inventory){
      inventory.Sort(
        delegate(PickUp p1, PickUp p2){
          return p1.description.CompareTo(p2.description);
        }
      );
    
      // rest of the method as before …
    }
  2. You should now see all the items listed in alphabetic sequence. This C# code takes advantage of the List.Sort(…) method, a feature of collections whereby each item can be compared to the next, and they are swapped if in the wrong order (if the CompareTo(…) methods returns false).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.38