LevelSystem

    void Update ()
    {
        if(PlayerXp >= 0 && PlayerXp < 2000)
        {
            PlayerLevel = 1;
        }

        if(PlayerXp >= 2000 && PlayerXp < 5000)
        {
            PlayerLevel = 2;
        }

        if (PlayerXp >= 5000 && PlayerXp < 10000)
        {
            PlayerLevel = 3;
        }

        Xp.text = " " + PlayerXp;
        Lvl.text = " " + PlayerLevel;
    }

In that code i need to do level by level.
I don’t want to make that at every level:

if(PlayerXp >= lastLevelMaxXp && PlayerXp  < nextLevelMinXp)
{

}

ex:

if(PlayerXp >= 0 && PlayerXp  < 2000)
{

}

if(PlayerXp >= 2000 && PlayerXp  < 4000)
{

}

How i can do “lastLevelMaxXp” and “nextLevelMinXp” to can be calculated automatically?

If I assume your system correctly, it goes 1/2/5/10/20/50/100/200/500 etc? So basically there’s a set of 3 and then it multiplies everything by 10, ad infinitum?

So let’s start with an array of your main 3 values, and your multiplier:

int[] levelXPValues = new int[]{1, 2, 5};
int levelCycleMultiplier = 10;

Now, what we basically need is a function that takes a given level number and returns the XP value required for that level. From there you can use (playerXp >= GetLevelXP(x) && playerXp < GetLevelXP(x+1) ) in a loop as your if statement.

So for that function, you’ll want to use modulus - the remainder after division - to get the index in the array, and then for each cycle through that array, multiply by 10.

int GetLevelXP(int level) {
int arrayIndex = level % levelXPValues.Length; // 0, 1, or 2
int multiplierExponent = level / levelXPValues.Length;
return Mathf.Pow(levelCycleMultiplier, multiplierExponent) * levelXPValues[arrayIndex];
}

Also to note. You probably don’t want to be doing this in update. You should be able to award experience, then run a check for if the player “gains a level”. Plus, it gives you the chance to do some cool level up animation.

It’s much better than checking endlessly if a player levels up even when they are doing nothing to gain exp. Just a suggestion.

I tried this in update because i wanted to see if the code is working correctly. :))

Edit: is on update but when the player have 0 lives the lvl and xp is saved with PlayerPrefabs :))

At line:
return Mathf.Pow(levelCycleMultiplier, multiplierExponent) * levelXPValues[arrayIndex];

i have this error:
Cannot implicitly convert type ‘float’ to ‘int’

and

After i do, when i kill a enemy i get xp?

Oh, yeah, you will need to typecast the result from the exponent like:

... = (int)Mathf.Pow( ...