Many games involve the player picking up items. Perhaps the most common is the need to pick up a key to be able to pass through a doorway, as shown in the following screenshot:
In the 0423_04_11
folder you'll find some key images, and a crisscross image to apply to the terrain.
To display a text description of inventory objects, please follow these steps:
// file: PlayerInventory using UnityEngine; using System.Collections; public class PlayerInventory : MonoBehaviour { private bool isCarryingKey = false; private void OnGUI() { string keyMessage = "(bag is empty)"; if( isCarryingKey ) { keyMessage = "carrying: [ key ]"; } GUILayout.Label ( keyMessage ); } private void OnTriggerEnter(Collider hitCollider) { if( "key" == hitCollider.tag ) { isCarryingKey = true; Destroy ( hitCollider.gameObject ); } } }
The isCarryingKey
Boolean variable represents whether or not the player is carrying the key at any point in time.
In the OnGUI()
method the contents of the keyMessage
string is displayed via the GUILayout.Label()
method. The default value of this string tells the user that the players bag is empty, but an if
statement tests the value of isCarryingKey
. If that is true, then the message is changed to inform the user that the player is carrying a key.
The OnTriggerEnter()
method tests the tag
string of any object the player's character controller collides with that has its Is Trigger checkbox set to true.
Each time the player's character controller collides with any object that has its Is Trigger value set to true, an OnTriggerEnter()
event message is sent to both of the objects involved in the collision.
The OnTriggerEnter()
message is passed a parameter, which is the Collider
component inside the object it just collided with. Our character controller's OnTriggerEnter()
method tests the tag
string of the object it collided with to see if has the key
value.
Since the Cube–key cube that we created has its trigger set, and has the key
tag, then the if
statement inside this method will detect a collision with Cube–key and will perform the following two actions:
isCarryingKey
Boolean variable to true
Boolean variables are often referred to as flags
The use of a bool
(true/false) variable, to represent whether a particular feature of the game state is true or false, is very common. Programmers often refer to these variables as "flags". So programmers might refer to the isCarryingKey
variable as the key carrying flag.
Here are some details you don't want to miss:
Comparing the tag
string of a game object against a string is such a common task that Unity has provided a special method for just this purpose. This method is named CompareTag()
, and takes a string as its single argument. We can therefore rewrite the if
statement in the OnTriggerEnter
method a little more elegantly, as follows:
if( hitCollider.CompareTag("key") )
13.59.107.152