Picking up an Item and telling you how many you have

Hey guys, I am really new to Unity and I am having a problem. In my game, I am having the player pick up keys (6 in total) and I want the GUIText to say “Keys Collected: 1/6” and have it increment each time a key is picked up and then have the text disappear. I am so confused on how to do this and Ive been searching to the forums for help but I still don’t understand how to do this. I have some code up but it is not working correctly. Please help!

var keyAlert : GUIText ;
var key : int = 0;
function OnTriggerEnter (other : Collider) {
	if (other.gameObject.tag == "Player"){
		key += 1;
		alertKey ();
function alertKey(){
	keyAlert.text = "Keys Collected:" + key ;
	yield WaitForSeconds (3);
	keyAlert.text = "";

With scripts in Unity, each GameObject that has a script attached to it has a it’s own variable state. that means that Key A has it’s own value for “keyAlert” and “key” separate from keys B, C, D, E, F, and vice versa.

The key script you have written is waiting for a collision with the player, but each time there is a collision, you’re only updating that key’s “key” variable. Then soon after, you destroy the key’s GameObject, which destroys all the data attached to it, including your script variables attached to it.

There are two ways to go about this, one gets the job done but has a bad design. The other has a better design and does the same thing.

  1. There is a way to share a variable between objects of a type. If you name “key” as a static variable, it is a value where memory is shared between all

    static var key : int = 0;

Then, when one key dies, the shared memory is not destroyed.

  1. The previous way works, but its bad design because it goes against an object-oriented design principle called the Single Responsibility Principle. The keys shouldn’t do more than be keys. That is, you shouldn’t make them both inventory counters and keys, because it just complicates things. So, instead of having the keys check for player collision and checking the inventory count, you should reverse the relationship - the player should be the one doing what this script does.

To rewrite the script so it is no longer a Key script but an Inventory script:

A) Attach it to the player

B) Make all your key GameObjects have a Key tag

C) Make OnTriggerEnter check for “Key” tag instead of “Player” in the if statement.

D) Have it destroy other.gameObject instead, which is the key.