Managing inventories with a general purpose PickUp class

There are often several different kinds of items players are expected to pick up and collect during a game (keys, extra lives, items that score points, and so on). A general PickUp class to represent the properties for each pickup item can be very useful, and the GUI display of inventory items can be made straightforward using a C# List<T> collection of such objects.

Managing inventories with a general purpose PickUp class

Getting ready

In the 0423_04_13 folder you'll find a selection of images and icons for keys and hearts.

How to do it...

To display graphical icons for a general purpose inventory, please follow these steps:

  1. Create a new scene and add a directional light.
  2. Create a new terrain size, with Size set to 2000 x 2000 and positioned at (-1000, 0, -1000). Now, apply a texture to it.
  3. Create the following C# script class:
    // file: PickUp.cs
    using UnityEngine;
    using System.Collections;
    
    public class PickUp : MonoBehaviour {
      public enum PickUpCategory{
        KEY, HEALTH, SCORE
      }
      
      public Texture icon;
      public int points;
      public string fitsLockTag;
      public PickUpCategory catgegory;
    }
  4. Import the built-in Character Controller Unity package and add a 3rd Person Controller to your scene at position (0, 1, 0).
  5. Attach the following C# script class to your 3rd Person Controller:
    // file: GeneralInventory.cs
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class GeneralInventory : MonoBehaviour {
      const int ICON_HEIGHT = 32;
      private List<PickUp> inventory = new List<PickUp>();
      
      private void OnGUI(){
        // restrict display to left of screen
        Rect r = new Rect(0,0,Screen.width/2, ICON_HEIGHT);
        GUILayout.BeginArea(r);
        GUILayout.BeginHorizontal();
        
        DisplayInventory();
        
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
      }
      
      private void DisplayInventory(){
        foreach (PickUp item in inventory)
            GUILayout.Label( item.icon );
      }
      
      private void OnTriggerEnter(Collider hitCollider){
        if( "pickup" == hitCollider.tag ){
          PickUp item = hitCollider.GetComponent<PickUp>();
          inventory.Add( item );
          Destroy ( hitCollider.gameObject );
        }
      }
    }
  6. Create a cube named Cube – health at position (0, 1, 5) with scale (2, 2, 2), and do the following (use the next screenshot as a reference):
    • Tag this objet with pickup
    • Tick its Is Trigger checkbox
    • Add the PickUp script class as a component of this object
    • Drag the heart icon into the Inspector view for the corresponding public variable
    • Choose HEALTH form the Category dropdown list
    • Add the heart image to the material for this object
    How to do it...
  7. Make several duplicates of Cube – health, and change some of them to have colored key images and icons as appropriate. This will ensure that there are several different items for the player to pick up in your game.

How it works...

The PickUp class has no methods, but it declares several useful public variables. It also declares a public enum category defining three possible categories of pickups: KEY, HEALTH, and SCORE. Each object of the PickUp class can define an image icon, an integer number of points, a string (for key items, the tag of locks that such a key would fit), and which of the enum categories each PickUp item belongs to.

Game objects can have a scripted object of the PickUp added as a component. In this recipe, cubes with images to illustrate what they are have been used, but the game objects the player meets in the game world could be interactive 3D objects or whatever. Each game object with a PickUp component needs to have its properties set appropriately. For example, yellow key objects should have a yellow key icon assigned, be set as being in the KEY category, and have the tag string set for locks it can open.

The player's character controller has the GeneralInventory script added. This is a relatively straightforward GUI script that has two main functions: first, it maintains a List<T> collection of PickUp objects, representing items the player is "carrying" at any point in time, and it displays the icons for each item via the OnGUI() method. Second, it detects collisions with pickup game objects via the OnTriggerEnter() method, and objects tagged pickup that are collided with are added to the inventory list.

There's more...

Here are some details you don't want to miss:

Responding to non-display pickups

By having different categories of pickups, the actions for collisions can be different. So perhaps for HEALTH pickups, the Points value is added to the player's health, and the object is destroyed rather than being added to the inventory. This would simply require an if or a case statement inside the OnTriggerEnter() method to decide what to do once an object tagged pickup has been collided with.

Removing items from the List<> collection

Events may occur (for example, open a door for a key being carried) that result in an item needing to be removed from the inventory List<>. For example, if a yellow door were collided with, and the player was carrying a key that could open such doors, then that item should be removed from the inventory List<> collection and the door be opened. To implement this, you would need to add an if statement test inside OnTriggerEnter() to detect a collision with the item tagged yellowDoor:

if( "yellowDoor" == hitCollider.tag )
  OpenDoor(hitCollider.gameObject);

The OpenDoor() method would need to identify which item (if any) in the inventory can open such a door, and if found, then that item should be removed from the List<> collection and the door be opened by the appropriate method:

private void OpenDoor(GameObject doorGO){
  // search for key to open the tag of doorGO
  int colorKeyIndex = FindItemIndex(doorGO.tag);
  if( colorKeyIndex > -1 ){
    // remove key item
    inventory.RemoveAt( colorKeyIndex );
    
    // now open the door ...
    doorGO.animation.Play ("open");
  }
}

private int FindItemIndex(string doorTag){
  for (int i = 0; i < inventory.Count; i++){
    PickUp item = inventory[i];
    if( item.fitsLockTag == doorTag )
      return i;
  }
}

See also

  • The Displaying inventory text for single object pickups recipe.
  • The Displaying inventory icons for single object pickups recipe.
..................Content has been hidden....................

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