- Home /
C# Do something every 100 points?
I have a score script that increases the score over time, but I am wondering how I could do an action on every 100 points, here is what I got so far:
void FixedUpdate () {
if (scoreTimer == true) {
scoreCount += 0.005f * speedUp.move;
scoreText.text = scoreCount.ToString ("F0");
}
if (scoreTimer == false)
{
scoreCount +=0.0f;
scoreText.text = scoreCount.ToString("F0");
PlayerPrefs.SetFloat("Player Score", scoreCount);
}
}
I have looked around for solutions but not really sure where to start.
I thought about doing something like this:
if (scoreCount == 100) {
"Do something"
{
But that wouldn't update every 100 score only the first time.
Thanks in advance :)
Answer by Huacanacha · Mar 27, 2015 at 08:33 AM
Given that you seem to be dealing with floats, or even if not then with scores that can increase by varying amounts, you can't use direct comparison with 100 (or even the modulus: scoreCount % 100 == 0
).
I would set a target score for the next action then increment the target each time it is reached.
float targetScore = 100;
void FixedUpdate() {
...
if (scoreCount >= targetScore) {
// Do something
targetScore += 100;
}
}
$$anonymous$$odulus is very handy when you're working with integers. However, in your case @da_st you're working with floats which means that the score won't necessarily be equally divided by 100 - your score could for instance be 100.5 which wouldn't trigger the solution you have tried.
I certainly agree with @Huacanacha. His solution would probably be the simplest. The targetScore can easily be adjusted and thus set a new "goal" before another action triggers.
@da_st Don't forget to mark it as an answer if it helped you.
In this case modulus would not be appropriate even if the score is an int. Score could increase by more than 1 each frame (199 -> 203) thereby skipping the triggering condition.
$$anonymous$$odulus + equality should only be used in this manner where you can guarantee the increments between checks, for example inside a for loop.
Your answer
Follow this Question
Related Questions
Scoring Points. 1 Answer
How to add score after destroying object in unity 2D? 1 Answer
Multiply float by int? 2 Answers
Need Help with Dual Scoring System C# (score over time and kill score) 1 Answer
Adding coin score to multiplied value 2 Answers