I’m trying to implement an exponential level-up system based on Runescape’s. It seems to be working just as intended, but there is one issue: Whenever I start the game, it starts off level 2 instead of 1, while the required XP is 83, which is the required XP for level 2. So it’s correct with requiring 83 XP, but it shouldn’t start off Level 2.
Here’s my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LevelUpSystem : MonoBehaviour
{
public int currentLevel;
public int XP = 0;
public int reqXP = 83;
public TextMeshProUGUI levelGUI;
public TextMeshProUGUI reqGUI;
// Update is called once per frame
void Update()
{
levelGUI.text = currentLevel.ToString();
reqGUI.text = reqXP.ToString();
if (Input.GetKeyDown(KeyCode.T))
{
GainXP(10);
}
// We use "while" instead of "if" in case the player levels up multiple times.
while (XP >= reqXP)
{
LevelUp();
}
}
void GainXP(int amount)
{
XP += amount;
Debug.Log($"Gained {amount} XP. Total XP: {XP}");
// Check if the XP exceeds the requirement and level up if needed
while (XP >= reqXP)
{
LevelUp();
}
}
public void LevelUp()
{
currentLevel++;
XP -= reqXP; // Reset XP, maintaining overflow
Debug.Log($"Level Up! New Level: {currentLevel}");
int firstPass = 0;
//This is the formula that calculates exponential increase and level up cycles
for (int levelCycle = 1; levelCycle < currentLevel; levelCycle++)
{
firstPass += (int)Math.Floor(levelCycle + (300f * Math.Pow(2f, levelCycle / 7f)));
Debug.Log(levelCycle);
}
reqXP = firstPass / 4;
Debug.Log($"Required XP for next level: {reqXP}");
}
}
This is how the screen looks (including the debug log)
So far I have tried things like setting the current level at 1 at the start, but it seems to ignore that and just calculates everything within the formula.
Ilija Spasovic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.