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);
}
}
}
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.
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).