- Home /
Destroy + Score
I need destroy object which i click and add some points to score. All objects what i clicking destroying fine but points adds only one time. whats wrong?
public class Coins : MonoBehaviour {
public GUIText cointext;
public int curCoins;
public int maxCoins = 10;
public int X = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseDown() {
if (gameObject.tag == "element") {
print ("+ " + X);
X++;
Destroy(this.gameObject);
}
}
}
You wanted points to be added more than once for a gameObject that you've Destroy()'ed?
You want to collect points, so they increase for every obtject, that you destroy? You can't do it this way, because every object, starts with it's own X = 0. $$anonymous$$eaning if you click on 10 objects the X won't become 10. You need Game$$anonymous$$anager script, that every object is sending information to...
Answer by rutter · Feb 14, 2014 at 11:07 PM
The way you've declared your variables, each Coins script has its own cointext
, curCoins
, maxCounts
, and X
.
Some of those values might make sense in another component (is "score" really a notion each coin should track, or is "score" something each player has?).
The following is just an example; it assumes that you have a GameObject named "Player" with a "PlayerScript" component that exposes a public function "GetCoin". We don't need to know what exactly GetCoin
does, but we can probably assume that it increases the player's score.
void OnMouseDown() {
GameObject player = GameObject.Find("Player");
PlayerScript playerScript = player.GetComponent<PlayerScript>();
playerScript.GetCoin();
Destroy(gameObject);
}
As an alternative, you could declare some of those as static fields:
static int score;
That way, the score
field is shared by all instances of the Coin
class. If other scripts need to access this data, you'll need to expose it publicly (consider making it read-only).
Your answer
Follow this Question
Related Questions
C# Make Child Not Animate Looped Animation 1 Answer
C# Check If Scripted Gameobject goes Past Variable Gameobject 0 Answers
C# GameObjectList not Setting Parent 0 Answers
C# Gameobject's Script's ValuesEquals Other Gameobject's script's Values 1 Answer
adding animation dynamically by script 0 Answers