Displaying inventory icons for single object pickups

The previous recipe communicated whether or not the player was carrying a key via text on screen. The use of graphical icons often results in a more engaging GUI.

Getting ready

In the 0423_04_12 folder, you'll find a key icon image, and an empty inventory icon image. In the 0423_04_11 folder, you'll find some key images, and a crisscross image to apply to the terrain.

How to do it...

To display graphical icons for individual inventory objects, please follow these steps:

  1. Create a new scene, and add a directional light.
  2. Create a new terrain, with Size set to 2000 x 2000 and positioned at (-1000, 0, -1000). Now, apply a texture to it.
  3. Create a cube named Cube–key at position (0, 1, 5) and with scale (2, 2, 2).
  4. Tag Cube–key with the key string, and tick its IsTrigger checkbox.
  5. Add a key image to Cube–key.
  6. Import the built-in Character Controller Unity package and add a 3rd Person Controller to your scene at position (0, 1, 0).
  7. Attach the following C# script class to your character controller:
    // file: PlayerInventoryIcon.cs
    using UnityEngine;
    using System.Collections;
    
    public class PlayerInventoryIcon : MonoBehaviour 
    {
      public Texture keyIcon;
      public Texture emptyIcon;
      
      private bool isCarryingKey = false;
      
      private void OnGUI()
      {
        if( isCarryingKey )
          GUILayout.Label( keyIcon );
        else
          GUILayout.Label( emptyIcon );
      }
      
      private void OnTriggerEnter(Collider hitCollider)
      {
        if( "key" == hitCollider.tag )
        {
          isCarryingKey = true;
          Destroy ( hitCollider.gameObject );
        }
      }
    }
  8. With the 3rd Person Controller selected in the Hierarchy view, drag the key icon and empty icon images into the Inspector view for the corresponding public variables.

How it works...

The two public Texture variables hold the icons for a key and an empty inventory. The OnGUI() method uses an if statement to test the value of isCarryingKey. If it is true, then a key icon image is displayed, if not, then an icon representing an empty inventory is displayed. The following screenshot shows an example of the statement being true:

How it works...

See also

  • The Displaying inventory text for single object pickups recipe.
  • The Managing inventories with a general purpose PickUp class recipe.
..................Content has been hidden....................

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