Pickup Counter Script

I'm making a pickup system for my game, but my script isn't working. When i mover over the cube, it is destroyed but my money counter doesn't go up.

var moneydisp : GUIText;
var money = 20;

function Update () {
    moneydisp.text = ""+ money;
}

function OnTriggerEnter() {
    money = money++;
    Destroy(gameObject);
}

what's going on here?

To increment an integer counter variable by 1, you just need to call the ++ operator, like this:

money++;

The reason for the strange behaviour in your script is that although the ++ operator increments the variable, it actually returns a different value - the value of the variable before it was incremented.

This means your variable gets incremented, but because you are putting the returned value back into the same variable, it gets immediately replaced with its original value.

An example, for clarification:

var a = 0;
var b = 5;

a = b++;

print(a);  // result is 5 (the original value of 'b', as returned by ++)
print(b);  // result is 6 (because b was incremented by the ++)

If you want to increment a variable by a value other than 1, you can use the similar += operator?

a += 4;  // increment 'a' by 4

Hope this helps clarify things!

In addition, there seems to be some confusion about which object does the counting, and displaying of the money sum. The script that detects the collection of the money & adding should be on your player, rather than on the money object. Make sure your money objects are tagged "Money", then place this script on your player:

var moneyDisplay : GUIText;
var money = 20;

function Start() {
    DisplayAmount();
}

function DisplayAmount () {
    moneydisp.text = ""+ money;
}

function OnTriggerEnter(other : Collider) {
    if (other.CompareTag("Money")) {
        money++;
        DisplayAmount();
        Destroy(other.gameObject);
    }
}

Remember to make sure that:

  • all money objects are tagged "Money"
  • all money objects have a trigger collider
  • the player object has either a CharacterController or rigidbody & collider
  • the "moneyDisplay" variable reference is linked up in the inspector

So, the above script (which is placed on the player) detects if the player touches a "Money" object. This single script counts the money total, and is responsible for displaying the amount, and for destroying the money object.

The money objects themselves need no script attached at all.

To make things a bit cleaner I like to add a tag to the gameobjects that are acquirable, though it is optional. In the case that you'd like to avoid that simply take out the 'if' statement in the beginning of the second function.

var moneydisp : GUIText;
var money = 20;

function Update () 
{
    moneydisp.text = ""+ money;
}

function OnTriggerEnter()
{
if(gameObject.tag == "money")
    {   
        Debug.Log("You have picked up money");
        Destroy(gameObject);
        money++;
    }
}