- Home /
How to have score when an object is destroyed
I'm sorry but i'm new to unity and not very good with javascript. I just want to add score when an object is clicked and destroyed.This is all i have.
function OnMouseDown () {
Destroy(gameObject);
}
Any help is appreciated.
Answer by aldonaletto · Nov 02, 2013 at 12:47 AM
If you will have only one score variable for the whole game, declare it as static like this:
static var score: int;
function OnMouseDown () {
Destroy(gameObject);}
score++; // increment score
}
Supposing that this script is called BubbleScript.js, for instance, you can access the static variable score in any other script as BubbleScript.score. If you have a GUIText that shows the current score, its script could be like this:
private var lastScore: int; // used to detect when the score changes
function Update(){
// only change the GUIText string when the score has changed
// this avoids unnecessary memory allocation, improving performance
if (BubbleScript.score != lastScore){ // if score changed...
guiText.text = "Score: " + BubbleScript.score; // update GUIText...
lastScore = BubbleScript.score; // and lastScore
}
}
NOTE: Be aware that static variables are created only once when the game starts and survive to level changes, thus score won't be reset when changing to other levels - you must explicitly assign zero to it when you want to clear it.
Your answer
Follow this Question
Related Questions
How to keep score? 1 Answer
Destroying gameobject 2 Answers
Scoring (i'm stuck) 3 Answers
How to make a saved score destroy on load new scene 0 Answers
I want to use the current scale x of my object to help calculate my score. . . 1 Answer