Q1. This is driving me nuts. I’m trying to make a level up system, but i’m too much of a newbie to do it it seems. So I wrote this code:
if (score >= 10) {
speed = 20.0f;
levelUpNow ();
}
if (score >= 20) {
speed = 25.0f;
levelUpNow ();
}
But this just endlessly executes the levelUpNow function. I want it to execute just once, then on score 100 do the same, once.
I imagine it’s because once the score reaches 10 it’s always 10 or above, so that’s why it makes a loop, but I’ve no idea how to prevent it. I tried doing if (score == 10) but that didn’t work at all.
Can anyone help me make this possible? Or…
Q2. Is it possible to do something like this:
if score == (10, 20, 30, 40, 50, 60, 70, 80, 90 ,100) then levelUpNow();
Basically execute the funtion everytime you reach a score of one of the above values.
It’s because you don’t have a value, typically an int in your case, to keep track of the current level.
public class YourClass : MonoBehaviour
{
// This value will keep track of the current level and prevent wrong level ups
private int currentLevel = 0;
void Update()
{
if (currentLevel < 1 && score >= 10) {
speed = 20.0f;
levelUpNow ();
currentLevel++;
}
if (currentLevel < 2 && score >= 20) {
speed = 25.0f;
levelUpNow ();
currentLevel++;
}
}
}
For your second question, yes, you could make a loop:
public class YourClass : MonoBehaviour
{
// This value will keep track of the current level and prevent wrong level ups
private int currentLevel = 0;
private int[] levelUpScores = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
void Update()
{
while (score >= levelUpScores[currentLevel] && currentLevel < levelUpScores.Length) {
speed += 5f; // This will increment the speed 5f at each level
levelUpNow ();
currentLevel++;
}
}
}
Note that in this example:
- the speed will increase linearly, 5f at each level,
- the last level is level 10; the score will increase without level change.