- Home /
Other
Variable goes very high in update method
Hello all. So basically I'm working on a thing and based of a score variable, I want my speed variable to increase. However, the variable goes very high in the for loop. I assume this is because it is in the update method which checks it very quickly so it goes high up. Is there a way to make not have this happen? Here is the code:
void Update()
{
int[] levelNums = { 5, 10, 20, 30, 40, 50 };
for (int i = 0; i < 6; i++)
{
if (score == levelNums[i])
{
speed+= 5;
}
}
~Thanks in advance.
If the speed is increasing too fast, why not just increment it by a smaller amount?
it is not clear what you want to do. do you want the speed to increase slowly over a fixed time? do you want the speed to match the level number?
no so if my score is equaled to any of the values in my levelNums array, increase the speed by 5. Now the issue is if score is equaled to levelNums[i], then speed goes up to much because update is checked very frequently.
public float timer = 0;
void Update()
{
float seconds = 1;
timer += Time.deltaTime;
if(timer>seconds){timer-=seconds;
{
//now this happens once per second
int[] levelNums = { 5, 10, 20, 30, 40, 50 };
for (int i = 0; i < 6; i++)
{
if (score == levelNums[i])
{
speed+= 5;
}
}}
Answer by king_opping · Jan 21, 2019 at 05:20 AM
i think you need to add 1 more varible to stop speed for incrementing,
public bool leveled;
void Update()
{
int[] levelNums = { 5, 10, 20, 30, 40, 50 };
for (int i = 0; i < 6; i++)
{
if (score == levelNums[i] && leveled==false)
{
if(leveled==true){leveled=false;}
else{speed+= 5;
leveled = true;}
}
}
These two lines of code don't make any sense
if (score == levelNums[i] && leveled==false)
if(leveled==true){leveled=false;}
The second line of code can never happen. It's basically dead code and you can delete it.
The whole thing can be simplified to
public bool leveled;
void Update()
{
int[] levelNums = { 5, 10, 20, 30, 40, 50 };
for (int i = 0; i < levelNums.Length; i++)
{
if (score == levelNums[i] && !leveled)
{
speed += 5;
leveled = true;
}
}
}
yes, thanks mate. i just recognize it. change that to your need, i cant figure it out right now,