Hi all! I’m struggling with a problem. I need to create a script that allow me to increase some counters value indipendent one from another, but the total value of each of them must be stored on a total counter. For example:
Counter_1 increase it’s value from 0 to 1.
Counter_2 increase it’s value from 0 to 1.
Counter_3 increase it’s value from 1 to 3;
TotalCounter = Sum of all precedent counters’ values.
Also, here’s an image:
I’m not sure if I’ve been clear enough, I do hope so. If you need any other info, just ask. Thank you all!
Assuming your using ints, just have an int variable for each counter and an int variable for the total. Whenever score changes, pass the value of the change to a method that adjusts the total.
Edit: Probably should put some sample code here. Probably better way to write it.
// whatever event causes player score to increment - do for each player
int increment = 1; // amount to raise by
player_1_Score = player_1_Score + increment
AdjustTotal (increment);
Use collection and loops. Lists or arrays. Lists if the amount of scores need to be dynamic.
//List of scores
private List < int > scores = new List < int > ();
void Start() {
//Init 6 scores to zero
for (int counter = 0; counter < 6; counter++) {
scores.add(0);
}
}
//Flag indicating whether we need to recalc the total
private bool _bSumTotal;
public bool bSumTotal {
get {
return _bSumTotal;
}
set {
_bSumTotal = value;
}
}
private int _totalScore;
//A getter that is also a setter
public int totalScore {
get {
if (bSumTotal)
{
//Recalc the score
int newScore = 0;
for (int counter = 0; counter < scores.count; scores++)
{
newScore += scores[counter]
}
//Set the flag back to false
bSumTotal = false;
//Overwrite and return the score
_totalScore = newScore;
return _totalScore;
}
else {
//current score is already up to date
return _totalScore;
}
}
}
/
Then whenever you do something that requires you to recalculate the score next time you fetch it, just set the bSumTotal flag to true. You would set to true every time a score is modified, added, or removed from the list.
public void IncreaseAchievementValue(int score, Text TierValue) {
if (score < 3) {
score++;
TierValue.text = score.ToString();
_bSumTotal = true;
}
}