x


How to add money?

I have chests that open and give me money. When I open the first chest it gives me 500, but when I open a second chest it is adding the new amount to the original money amount of 0 and I am still left with 500. here is my code please help:

var money : int;
var GUIMoney : GUIText;
var target : Transform;
var moneyAmount : int;

function OnTriggerEnter( other : Collider ) { 
    if (other.tag == "Player") {
        money+= moneyAmount; 
        GUIMoney.text = money.ToString();
        Destroy(other.gameObject); 
    } 
}

function Update(){
    MoneyPU();
}

function MoneyPU(){
    distance = Vector3.Distance(target.transform.position, transform.position);

        if(distance < 2){
            if(Input.GetButtonDown("Activate")){
                yield WaitForSeconds(1);
                money+= moneyAmount; 
                GUIMoney.text = money.ToString();
                Destroy (this);

            }
        }
}
more ▼

asked Sep 16 '10 at 11:32 AM

MonkeyAssassin8 gravatar image

MonkeyAssassin8
271 35 38 43

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You need to store "money" and "moneyAmount" in different scripts (or instances) because at the moment each script is updating its own money amount which will always be 0. Store the player's money on the player object or a game controller object separate from the pickups.

e.g.

money script:

var moneyAmount : int = 500;

function OnTriggerStay( other : Collider ) { 
    // check for player tag and active button
    if (other.tag == "Player" && Input.GetButtonDown("Activate")) {
        // send a message to the player object
        other.gameObject.SendMessage("AddMoney",moneyAmount); 
        // removed the money
        Destroy(gameObject); 
    } 
}

player script:

var money : int = 0;
var GUImoney : GUIText;

function AddMoney(amount :int){
    money += amount;
    GUIMoney.text = money.ToString();
}
more ▼

answered Sep 16 '10 at 12:37 PM

spinaljack gravatar image

spinaljack
9.1k 18 31 91

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x68
x47
x27
x2

asked: Sep 16 '10 at 11:32 AM

Seen: 962 times

Last Updated: Sep 16 '10 at 11:32 AM