When several items of the same type have been picked up, often the simplest way to convey what is being carried to the user is to display a text message showing the numeric total of each item type being carried, as shown in the following screenshot. In this recipe, the total number of stars collected is displayed using a UI Text object.
This recipe assumes you are starting with project Simple2Dgame_SpaceGirl
setup from the first recipe in this chapter. The font you need can be found in folder 1362_02_02
.
To display inventory total text for multiple pickups of same type of object, follow these steps:
Simple2Dgame_SpaceGirl
.Text-carrying-star
. Change its text to stars = 0.Fonts
folder into your project.Text-carrying-star
to Xolonium-Bold (folder Fonts
) and set its color to yellow. Center the text horizontally and vertically, and set its Font Size to 32
.50
. Edit its Rect Transform, and while holding down SHIFT and ALT (to set pivot and position), choose the top-stretch box. Your 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.Player
to GameObject player-SpaceGirl
in the Hierarchy:using UnityEngine; using System.Collections; using UnityEngine.UI; public class Player : MonoBehaviour { public Text starText; private int totalStars = 0; void Start(){ UpdateStarText(); } void OnTriggerEnter2D(Collider2D hit){ if(hit.CompareTag("Star")){ totalStars++; UpdateStarText(); Destroy(hit.gameObject); } } private void UpdateStarText(){ string starMessage = "stars = " + totalStars; starText.text = starMessage; } }
player-SpaceGirl
. Then, from the Inspector, access the Player (Script) component and populate the Star Text public field with UI Text object Text-carrying-star
.star
in the Hierarchy panel and make three more copies of this GameObject.The Text
variable starText
is a reference to the UI Text object Text-carrying-star
. The int
variable totalStars
represents how many stars have been collected so far; it is initialized to zero.
In the OnTriggerEnter2D()
method, the totalStars
counter is incremented by 1 each time the player's character hits an object tagged Star. The collided star GameObject is destroyed and a call is made to the UpdateStarText()
method.
The UpdateStarText()
method updates the text content of UI Text object Text-carrying-star
with text string stars =
concatenated with the integer value inside variable totalStars
to display the updated total number of stars to the user.
18.227.102.159