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.
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.
To display inventory total text for multiple pickups of different object types, follow these steps:
Simple2Dgame_SpaceGirl
.star
GameObject now has the tag Pickup.PickUp
to GameObject star
in the Hierarchy:using UnityEngine; using System.Collections; public class PickUp : MonoBehaviour { public string description; }
star
to the text star
, as shown in the following screenshot:star
in the Hierarchy panel and make a copy of this GameObject, renaming the copy heart
.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.star
in the Hierarchy panel and make a copy of this GameObject, renaming the copy key
.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.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); } } }
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.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.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.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; } }
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
.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
.
Some details you don't want to miss:
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.
To implement the alphabetic sorting of the items in the inventory
list, we need to do the following:
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 … }
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).3.16.137.38