Graphic icons are an effective way to inform the player that they are carrying an item. In this recipe, if no star is being carried, a grey-filled icon in a blocked-off circle is displayed; then, after the star has been picked up, a yellow-filled icon is displayed, as shown in the following screenshot.
In many cases, icons are clearer (they don't require reading and thinking about) and can also be smaller onscreen than text messages for indicating player status and inventory items.
This recipe assumes that you are starting with the project Simple2Dgame_SpaceGirl
setup from the first recipe in this chapter.
To toggle carrying and not-carrying icons for a single object pickup, follow these steps:
Simple2Dgame_SpaceGirl
.Image-star-icon
.Image-star-icon
in the Hierarchy panel.Sprites
) into the Source Image field in the Inspector (in the Image (Script) component).Player
to GameObject player-SpaceGirl
in the Hierarchy:using UnityEngine; using System.Collections; using UnityEngine.UI; public class Player : MonoBehaviour { public Image starImage; public Sprite iconStar; public Sprite iconNoStar; private bool carryingStar = false; void OnTriggerEnter2D(Collider2D hit){ if(hit.CompareTag("Star")){ carryingStar = true; UpdateStarImage(); Destroy(hit.gameObject); } } private void UpdateStarImage(){ if(carryingStar) starImage.sprite = iconStar; else starImage.sprite = iconNoStar; } }
player-SpaceGirl
. Then, from the Inspector, access the Player (Script) component and populate the Star Image public field with UI Image object Image-star-icon
.icon_star_100
and populate the Icon No Star public field from the Project panel with sprite icon_nostar_100
, as shown in the following screenshot:The Image
variable
starImage
is a reference to the UI Image object Image-star-icon
. Sprite
variables iconStar
and iconNoStar
are references to the Sprite
files in the Project panel—the sprites to tell the player whether or not a star is being carried. The bool
variable carryingStar
represents internally as program data whether or not the player is carrying the star at any point in time; it is initialized to false
.
Much of the logic for this recipe is the same as the previous one. Each time the UpdateStarImage()
method is called, it sets the UI Image to the sprite that corresponds to the value of bool variable carryingsStar
.
18.216.88.54