0

I'm making an endless runner game with Unity and in this game for every 10 coins I collect, it increases the level by 1 with a maximum of 10. Currently, I'm doing this:

IF(coins >= 10 and coins < 20) level = 2
IF(coins >= 20 and coins <= 30) level = 3

and so on till level 10.

But I'm sure that this code is badly written, I'm thinking in use the for statement but I'm a newbie to C#, any ideas?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Al Simmons
  • 17
  • 5
  • 4
    Simply level = coins / 10 + 1. This will give you the whole part of the division. For example: 0 / 10 + 1 = 1 16 / 10 + 1 = 2 23 / 10 + 1 = 3 – funatparties Feb 06 '22 at 15:39
  • Small tip, for `if` blocks like this non future, you only need one test, because they go in order. `if(x < 10).. else if (x<20) ... else if (x < 30)` - testing for >= 10 is redundant because by definition if something is not less than 10 it must be >= 10 – Caius Jard Feb 06 '22 at 20:07

3 Answers3

1

Use the modulo operator % to check if the number divided by 10 has the remainder of 0.

Example:

if (coins > 0 && coins % 10 == 0 && level < 10)
{
    ++level;
}

In this example we also check if the player has at least one coin as 0 % 10 == 0 returns true and you don't want the player to level up if they don't have any coins. You could skip that if the player's initial level is 0, but I guess it would be 1.

When it comes to leveling up, use the unary operator ++ as it's generally a rule of thumb if you want to increment a value by 1.

Suggested reading:

rbrt
  • 36
  • 5
1

try this

var level = coins < 90 ? (coins / 10 + 1) : 10;
Serge
  • 40,935
  • 4
  • 18
  • 45
0

use mod operation with 10

if(coins%10 == 0)
{
    level = coins / 10;
}
else
{
    level = (coins / 10) + 1;
}

// then check if level is bigger than 10
if(level > 10)
{
    level = 10;
}
Hunter Tran
  • 13,257
  • 2
  • 14
  • 23
  • This code exhibits different behavior than OP's code - in the question, `>=10` is level 2, not 1, for instance. In your case, `==10` is level 1. Also, level 3 in OP's code appears to either be a typo, or breaks the pattern... – CoolBots Feb 06 '22 at 16:52
  • I don't see your point? I test the code. If coins = 1 -> level = 1. Coins = 11 -> level = 2, coins = 21 -> level = 3, etc. You can test the code here: https://dotnetfiddle.net/MauG23 – Hunter Tran Feb 06 '22 at 17:32
  • 10 coins are level 2 in the OPs code. In yours it's level 1. – Dominik Feb 06 '22 at 17:53
  • oh I see. Then op need to refine the pattern, or the code could be difficult to maintain – Hunter Tran Feb 06 '22 at 18:09