- Home /
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);
}
}
}
Answer by spinaljack · Sep 16, 2010 at 12:37 PM
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(); }
Your answer
Follow this Question
Related Questions
Add Fresh Script to Game Object 1 Answer
Add GameObject to GameObjectArray[] 3 Answers
How to assign a gameobject to a script that is added dynamically 1 Answer
How to add script to objects through Empty Child? (or other easier ways) 2 Answers
How to write a script which move the character when the it entered an area? 1 Answer